无法在控制器和视图中访问$ scope变量 - AngularJS

时间:2014-07-06 13:25:02

标签: javascript angularjs

我必须在控制器(GridSearchCtrl)中绑定几个下拉列表,即在另一个控制器(DiplomaProgramGridCtrl)中绑定。我正在尝试下面的代码,但它给了我错误 $ scope.advSearch未定义

  DiplomaProgramController.controller('GridSearchCtrl', ['$scope', 'DiplomaProgramService', 
      function ($scope, DiplomaProgramService) {

        $scope.loadDropDowns = function ($scope) {
          DiplomaProgramService.loadDropDowns('abcd').then(function (DiplomaProgram) {
            $scope.advSearch.depts = DiplomaProgram.depts;
            $scope.advSearch.degreesList = DiplomaProgram.degreesList;
            // Here it shows the list perfectly
            console.log($scope.advSearch.degreesList);
          });
       };
       $scope.loadDropDowns($scope);
       // Here it generates error i.e. $scope.advSearch is undefined
       console.log($scope.advSearch.degreesList);
}]);

视图如下所示

    <select id="ddlDegrees" name="degrees" ng-model="advSearch.DegreeLevelID" ng-options="a.DegreeLevelID as a.DegreeLevelName for a in degreesList" required>
        <option value="">-- select --</option>
    </select>

1 个答案:

答案 0 :(得分:0)

我的猜测是.then(函数)中的内容是异步的,因此在定义$ scope.advSearch之前执行console.log。

尝试这样做(我真的不知道承诺如何运作,所以$ scope。$ apply可能根本就不相关):

DiplomaProgramService.loadDropDowns('abcd').then(function (DiplomaProgram) {
    $scope.$apply(function() {
        $scope.advSearch.depts = DiplomaProgram.depts;
        $scope.advSearch.degreesList = DiplomaProgram.degreesList;
        // Here it shows the list perfectly
        console.log($scope.advSearch.degreesList);
    }
});

它仍然无法使用console.log,但它应该告诉Angular您的范围已更新并使您的视图正常工作。