繁体   English   中英

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

[英]cannot access $scope variables in controller and view - 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>

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

尝试改为执行此操作(我真的不知道promise如何工作,因此$ 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您的范围已更新,并使您的视图正常工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM