在工厂方法中数据更改后,AngularJS范围不会更新

时间:2014-01-06 20:24:02

标签: javascript angularjs

我觉得我在这里遗漏了一些明显的东西,但我仍然受到了阻碍。

我通过调用ThingFactory上的create函数来更新范围。但是当我从PromoteController引用范围时,范围仍然包含旧版本的Thing(ID为1)。

这似乎是我想要使用$ scope。$ apply()的地方,但这会导致'摘要已在进行中'错误。

我错过了什么?

var app = angular.module('app', ['ngRoute']);

  app.factory('ThingFactory', ['$http', '$q', '$routeParams', function ($http, $q, $routeParams) {

  var deferred = $q.defer();

  return {
      get: function(id) {

          var thing = {
              id: 393,
              name: 'Can I be gotten?',
              description: 'get'
          };
          deferred.resolve(thing);
          return deferred.promise;
      },
      save: function (thing) {
          console.log("ThingFactory -> CREATE");
          var thing = {
              id: 122,
              name: 'after create.',
              description: 'creatine'
          };
          deferred.resolve(thing);

          return deferred.promise;
      },
      init: function() {
          console.log("ThingFactory -> INIT");
          var thing = {
              id: 1,
              name: 'initial value',
              description: 'INIT'
          };
          deferred.resolve(thing);
          return deferred.promise;
      }
  };

}]);

app.config(function ($routeProvider, $locationProvider, $httpProvider) {
  $locationProvider.html5Mode(true);
  $routeProvider
      .when('/build', {
          templateUrl: '/build.html',
          controller: 'BuildController'
      })
      .when('/things/:id/promote', {
           templateUrl: '/promote.html',
           controller: 'PromoteController'
      })
});


app.controller('BuildController', function ($scope, $http, $location, ThingFactory) {
  // HERE I INITIALIZE THE THING
  ThingFactory.init().then(function(thing) {
      $scope.thing = thing;
  });

  $scope.saveNewThing = function() {
      // HERE I 'SAVE' THE THING
      ThingFactory.save($scope.thing).then(function(thing) {
          $scope.thing = thing;
          $location.path("/" + thing.id + "/promote");
      })
  }

});

app.controller('PromoteController', function ($scope, $http, $routeParams, ThingFactory) {
  // HERE'S WHERE THE THING ON THE SCOPE SHOULD HAVE AN ID OF 122,
  // BUT IS STILL 1
  var id = $routeParams.id;
  ThingFactory.get({id: id}).then(function(thing) {
      $scope.thing = thing;
  });
});

1 个答案:

答案 0 :(得分:2)

请创建一个var deferred = $ q.defer();对于你工厂的每一种方法。否则你总是使用相同的延迟,这可以通过init函数中的值来解决。