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