2015-02-07 69 views
-1

我无法获得控制器和服务之间的数据绑定工作。 我有一个控制器和一个进行HTTP调用的工厂。我希望能够从其他服务调用工厂方法并查看控制器属性得到更新。我尝试了不同的选择,但他们似乎都没有工作。任何想法将不胜感激。控制器和服务之间的Angularjs数据绑定

请在这里看到的代码:

http://plnkr.co/edit/d3c16z?p=preview

下面是JavaScript代码。

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

app.controller('MainCtrl', function($scope) { 
    $scope.name = 'World'; 
}); 

app.controller('EventDetailCtrl', ['$http', 'EventDetailSvc', '$scope', 
    function ($http, EventDetailSvc, $scope) { 

     this.event = EventDetailSvc.event; 

     EventDetailSvc.getEvent(); 
     console.log(self.event); 

     $scope.$watch(angular.bind(this, function() { 
     console.log('under watch'); 
     console.log(this.event); 
     return this.event; 

     }), function (newVal, oldVal) { 
     console.log('under watch2'); 
     console.log(newVal); 
     this.event = newVal; 
     }); 

    }]) 

    .factory('EventDetailSvc', ['$http', function ($http) { 

    var event = {}; 
    var factory = {}; 

    factory.getEvent = function() { 
     $http.get('http://ip.jsontest.com') 
     .then(function (response) { 
      this.event = response.data; 
      console.log('http successful'); 
      console.log(this.event); 
      return this.event; 

     }, function (errResponse) { 
      console.error("error while retrieving event"); 
     }) 
    }; 

    factory.event = event; 

    return factory; 

    }]); 

回答

0

在我看来,你已经将事件对象嵌套在工厂对象中。你应该直接返回事件,而不是用工厂包装。现在你需要调用EventDetailSvc.factory.event来访问你的对象。

相关问题