Angular $scope not available outside my function

十年热恋 提交于 2019-12-24 12:16:07

问题


Somewhat new to Angular and javascript. I have the following controller written use a factory service to access a local JSON file. Most of this code is derived (or completely taken) from this post by Dan Wahlin. I am unable to access the $scope.books variable outside of the function and cannot figure out why. The console.log inside the function gives me the object I am looking for, but the one outside returns undefined. What am I doing wrong here? Thanks.

app.controller('FormController', ['$scope', 'tocFactory', function ($scope, tocFactory) {

  $scope.books;

  getBooks();

      function getBooks() {
        tocFactory.getBooks().
          success(function(data, status, headers, config) {
            $scope.books = data;
            console.log($scope.books);
          }).
          error(function(data, status, headers, config) {
            // log error
     })
  }
  console.log($scope.books);
  }]);

回答1:


Because you are making an ajax and then executing the next line of code. Which doesn't mean you have guarantee that your ajax response is ready on execution of next line of code.

You could always gets its response value inside the success function of $http which gets called when ajax call executed successfully.

Read here How asynchronous call works?




回答2:


actually this isn't an issue of scope, but timing. The getBooks function is executed asynchronously, so when your console log happens it most likely will not have been bound to anything. You could test this easily with interval to see how this is happening:

app.controller('FormController', ['$scope', 'tocFactory', function($scope, tocFactory) {
  $scope.books;
  getBooks();
  function getBooks() {
    tocFactory.getBooks()
      .success(function(data, status, headers, config) {
        $scope.books = data;
        console.log($scope.books);
      })
      .error(function(data, status, headers, config) {
        // log error
      })
  }
  setInterval(function(){
    console.log($scope.books);
  }, 1000);
}]);



回答3:


You can use $q service to handle asynchronous code with promises :

app.controller('FormController', ['$scope', '$q', 'tocFactory', function ($scope,  $q, tocFactory)
{

    var getBooks = function()
    {
        var deferred = $q.defer();

        tocFactory.getBooks().
        success( function(data, status, headers, config)
        {
            $scope.books = data;
            deferred.resolve();
        } ).
        error( function(data, status, headers, config)
        {
            deferred.reject();
        } );

        return deferred.promise;
    };

    getBooks().then( function(res)
    {
        console.log($scope.books); // success : your data
    }, function(res)
    {
        console.log($scope.books); // error : undefined
    } );

    console.log($scope.books); // undefined

} ] );

I haven't tested this code but it should work and show you promises principle. More about $q service : https://docs.angularjs.org/api/ng/service/$q



来源:https://stackoverflow.com/questions/32081084/angular-scope-not-available-outside-my-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!