问题描述
控制器中绑定服务/工厂变量,除非工厂变量是通过$ HTTP启动完美的作品。任何人都可以解释为什么?
Binding a service/factory variable within a controller works perfectly unless the factory variable is initiated through $http. Can anyone explain why?
注:由于controller.someVariable = factory.someVariable不起作用。目前,我直接引用工厂变量作为操纵
factory.someVariable
NOTE: Since controller.someVariable = factory.someVariable doesn't work. Currently I am referencing the factory variable directly for manipulation asfactory.someVariable
控制器:
app.controller('SecondCtrl',function($scope,testFactory){
$scope.obj = testFactory.obj;
$scope.factory = testFactory;
$scope.jsonData = testFactory.jsonData; //Not Binding
//Accessing $scope.factory.jsonData works while $scope.jsonData doesn't
});
厂址:
app.factory('testFactory', ['$rootScope','$http',function ($rootScope,$http) {
var factory = {};
factory.obj = { 'name':'Jhon Doe'};
factory.jsonData;
factory.fromjson = function() {
$http.get("data.json")
.success(function(data){
factory.jsonData = data.result;
})
}
factory.fromjson();
return factory;
}]);
Plunker:
推荐答案
正如我在评论中所提到的,这是发生的原因是因为 $ scope.jsonData = testFactory.jsonData;
为值分配,而当这种分配发生不幸的值不是从服务器呢。其他分配工作,因为他们的参考任务。
As I've mentioned in the comments, the reason this is occurring is because $scope.jsonData = testFactory.jsonData;
is a value assignment, and unfortunately that value isn't available from the server yet when this assignment occurs. the other assignments work because they are reference assignments.
一个快速而肮脏的方式来解决,这将是申报 factory.jsonData = {};
而不是 factory.jsonData;
。这将改变呼叫的基准分配(目的是对象),并允许改变一个传播到其他
One quick but dirty way to solve this would be to declare factory.jsonData = {};
instead of factory.jsonData;
. This would change the call to a reference assignment (object to object) and allow changes to one to propagate to the other.
这篇关于Angularjs:数据绑定不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!