2014-01-06 28 views
1

我觉得我错过了某些显而易见的东西,但我仍然陷入困境。在工厂方法中更改数据后,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; 
    }); 
}); 

回答

2

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

+0

果然是这个问题!非常感谢您的快速观察。 – yalestar