AngularJS范围不会在我的控制器内部发生变化

时间:2014-08-11 15:59:27

标签: javascript angularjs

我无法在我的控制器$scope.loading函数中更新createProject()。范围 已更改,但页面上的值未更新,为什么?我尝试过apply(),但这只是一个错误:

Error: [$rootScope:inprog] http://errors.angularjs.org/1.2.19/$rootScope/inprog?p0=%24digest
    at Error (native)
    at http://ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.min.js:6:450
    at m (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.min.js:105:353)
    at k.$apply (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.min.js:113:31)
    at http://127.0.0.1:8004/static/js/controllers/project.js:56:27
    at J (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.min.js:100:424)
    at http://ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.min.js:102:64
    at k.$eval (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.min.js:112:319)
    at k.$digest (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.min.js:109:392)
    at k.$apply (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.min.js:113:100) 

HTML:

 <button ng-show="project.new" class="btn btn-primary" ng-click="actionCreateProject()"
                            spinner-button=loading>Create
                    </button>

指令:

app.directive('spinnerButton', function () {
    return {
        restrict: "A",
        transclude: true,
        template: "<div ng-transclude ng-hide='loading'></div>"
            + "<div ng-show=loading>Not a button!</div>",
        scope: {loading: "=spinnerButton"},
        link: function (scope, elem) {
            elem.bind("click", function () {
                scope.loading = true;
            });
        }
    };
});

在控制器内:

  var createProject = function () {
                var new_project_data = {
                    "title": $scope.project.title,
                    "description": $scope.project.description
                };

                var resource = httpFactory.post("project", new_project_data)


                resource.then(function (object) {



                   $scope.$apply(function(){
                         $scope.loading = false;
                   })


                });


            };

1 个答案:

答案 0 :(得分:1)

在您的电话中拨打$apply,您不需要在控制器中拨打$ apply。

  elem.bind("click", function () {
      scope.loading = true;
      scope.$apply();
  });