简体   繁体   中英

Is possible to access angularjs $scope from within a $scope.$apply call

Is it possible to access the $scope variables and functions from within a $scope.$apply call?

Below is a bogus example to demonstrate my point. As is shown, the someFunctionWithaCallbackParam is called when the controller starts and its parameter is used as the callback when the function completes.

Within the $scope.$apply , are the $scope variables and functions visible? If not then how does one access the $scope?

 angular
  .module('myController')
  .controller('ExampleController', ['$scope', function($scope) {

     $scope.data = [];

     someFunctionWithaCallbackParam(function(myList) {
        $scope.$apply(function() {
           for (var i = 0; i < myList.length; i++) {
              // Is $scope visible from here??
              $scope.addItem(myList[i]);
           }
        });
     }
     $scope.addItem(item) {
        // do stuff
        $scope.data.push(item);
     }
  }]);

Yes. As a best practice however, you should only assign variables and functions to scope that you are going to use in the view. I try and separate view and controller variables and functions.

//controller variable
var blocks = [];

//scope variable
$scope.buyers = [];

//controller function
var addBlock = function(block) {
    blocks.push(block);
}

//scope function
$scope.blah = function() {
    //do stuff
}

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