返回状态时,$ scope何时重新加载?

时间:2015-02-19 17:16:30

标签: javascript angularjs angularjs-scope ionic-framework

我在此控制器的父状态中有一个list对象。每次加载使用此控制器的状态时,$scope.items都会被清空,控制器必须再次从父作用域加载数据。

ListCtrl对应list州。父状态包含许多列表。

.controller('ListCtrl', ['$scope','$state','$timeout',
    function($scope, $state, $timeout) {
    console.log($scope.items); // undefined
    if(!$scope.items) { // always evaluates to true
        $timeout(function() {
            $scope.items = $scope.$parent.list.items;
        }, 500);
    } else { 
        console.log($scope.items); // never executes here
    }
}])

据我所知,AngularJS默认会缓存一些视图。这是否意味着缓存不适用于缓存视图中的范围变量?最重要的是,有没有办法缓存这个$scope.items,这样每次我返回这个状态时,都没有超时延迟?

3 个答案:

答案 0 :(得分:0)

作为AngularJS的初学者,我的理解是$ scope.items仅在当前控制器中定义。如果要在html内容中加载项目,只需在该指定的html标记中使用的控制器下定义项目。

我编造了toy example

angular.module('scopeExample', [])
.controller('MyController', ['$scope', function($scope) {
  $scope.username = 'World';

}]);

AngularJS Scope documentation上的类似。

答案 1 :(得分:0)

家长控制器

 .controller('parentController', ['$scope','$state','$timeout','$rootScope'
        function($scope, $state, $timeout, $rootScope) {
        $rootScope.items=['item 1','item 2'];
    }])

另一个控制器

.controller('ListCtrl', ['$scope','$state','$timeout','$rootScope'
        function($scope, $state, $timeout,$rootScope) {
        console.log($rootScope.items); // Should give the result
        if(!$scope.items) { // always evaluates to true
            $timeout(function() {
                $scope.items = $scope.$parent.list.items;
            }, 500);
        } else { 
            console.log($scope.items); // never executes here
        }
    }])

别忘了在上面添加$ rootScope。

答案 2 :(得分:0)

最终解决方案是检查$ rootScope.list.item是否已加载,而不仅仅是$ scope.item。

if(!$rootScope.list) {
    $timeout(function() { 
        $scope.items = $rootScope.list.items; 
    }, 1000);
} else { 
    $scope.items = $rootScope.list.items; 
}