0

当路由发生变化时,Angular 似乎会重新渲染整个视图。见这个例子:http: //jsfiddle.net/RSHG8/1/

html:

<div class="nav">
    <a href="#/one">One</a><a href="#/two">Two</a>
</div>
<div ng-app="app" id="ng-app">
    <div ng-view=ng-view></div>
</div>

var app = angular.module('app', []);

js:

app.config(function ($routeProvider) {
    $routeProvider.when('/one', {
        template: 'Template {{template}}<br>Enter some text: <input type="text" /> then click "Two"',
        controller: 'one'
    })
        .when('/two', {
        template: 'Template {{template}}<br>Click back to view "One" to see changes undone',
        controller: 'two'
    })
        .otherwise({
        redirectTo: '/one'
    });
});

app.controller("one", function ($scope) {
    $scope.template = "One";
});

app.controller("two", function ($scope) {
    $scope.template = "Two";
});

在视图之间切换时忘记用户输入的文本。这对于非角度的东西也将是一个问题。例如一个 jQuery 展开折叠插件。如果用户展开一定数量的元素,离开视图并返回,状态将重置为所有折叠的内容。

是否可以让 Angular 简单地显示/隐藏视图,而不是在路由更改时擦除重新渲染?

4

1 回答 1

0

您可以尝试将 ng-model 分配给输入标签并将值存储在父控制器中。

HTML

<div class="nav">
    <a href="#/one">One</a><a href="#/two">Two</a>
</div>
<div ng-app="app" id="ng-app">
    <div controller="AppCtrl">
        <div ng-view=ng-view></div>
    </div>
</div>

var app = angular.module('app', []);

JS

app.config(function ($routeProvider) {
        $routeProvider.when('/one', {
            template: 'Template {{template}}<br>Enter some text: <input type="text" ng-model="$parent.inputValue" /> then click "Two"',
            controller: 'one'
        })
            .when('/two', {
            template: 'Template {{template}}<br>Click back to view "One" to see changes undone',
            controller: 'two'
        })
            .otherwise({
            redirectTo: '/one'
        });
    });

    app.controller("AppCtrl", function AppCtrl($scope) {
        $scope.inputValue = "";
    });

    app.controller("one", function ($scope) {
        $scope.template = "One";
    });

    app.controller("two", function ($scope) {
        $scope.template = "Two";
    });
于 2014-01-22T17:11:05.690 回答