Angularjs: Databinding not working

拟墨画扇 提交于 2019-12-12 02:24:30

问题


Binding a service/factory variable within a controller works perfectly unless the factory variable is initiated through $http. Can anyone explain why?

NOTE: Since controller.someVariable = factory.someVariable doesn't work. Currently I am referencing the factory variable directly for manipulation as factory.someVariable

Controller:

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
});

Factory:

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: http://plnkr.co/edit/wdmR5sGfED0jEyOtcsFz?p=preview


回答1:


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.

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.



来源:https://stackoverflow.com/questions/33184189/angularjs-databinding-not-working

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