简体   繁体   中英

cannot access $scope variables in controller and view - AngularJS

I have to bind few drop-downs in a controller(GridSearchCtrl) ie in another controller(DiplomaProgramGridCtrl). i was trying the below code but it is giving me error $scope.advSearch is not defined

  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);
}]);

The view looks like this

    <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>

My guess would be that what's inside the .then(function) is asynchronous, so your console.log is executed before $scope.advSearch is defined.

Try doing this instead (I don't really know how promises work yet so $scope.$apply might not be relevant in that case at all):

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);
    }
});

It still won't work with the console.log, but it should tell Angular that your scope has been updated and make your view work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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