子控制器中的Angular Parent范围值

时间:2014-12-02 21:12:42

标签: angularjs controller scope

我必须指出:Dashboard和Dashboard.Accounts。 每个都有自己的控制器,DashboardCtrl是AccountsCtrl的父控制器。 问题是如何在子控制器中访问父控制器中的范围var? 我试着写入AccountCtrl

console.log($scope.var);

但它告诉我 undefined

家长控制器:

.controller("DashboardCtrl", ["$scope", "$location", "userSvc",function ($scope, $location, authenticationSvc, userSvc) {
    $scope.getAccounts = function() {
        userSvc.getAccounts($scope.userInfo.accessToken, $scope.userInfo.companyId).
            then(function (result) {
                $scope.accounts = result;
            }, function (error) {
                console.log(error);
            });
    };
    $scope.getAccounts();
}])

userSvc中的getAccounts函数:

function getAccounts(accessToken, companyId) {
        var deferred = $q.defer();
        $http({
            url: "/api/accounts"
            method: "GET",
            headers: {'Content-Type': 'application/json'}
            }).
            then(function (result) {
                if(result.data.error === 0) {
                    accounts = result.data.data;
                    deferred.resolve(result.data.data);
                }
                else {
                    deferred.reject(error);
                }
            }, function (error) {
                deferred.reject(error);
            });
        return deferred.promise;
    };

最后是AccountCtrl:

.controller("AccountCtrl", ["$scope", "$location", "$window", "$state", "$stateParams", "userSvc", function($scope, $location, $window, $state, $stateParams, userSvc) {
  console.log($scope.accounts);
};

1 个答案:

答案 0 :(得分:1)

这不会起作用,因为在AccountCtrl函数运行时,$scope.accounts仍未定义 - 一旦您的promise异步解析,它就会被定义。

如果您想在$scope.accounts中对此事件作出反应,那么您应该使用$watch

$scope.$watch("accounts", function(){
  console.log($scope.accounts);
});