在我看来,我绑定到服务属性,该服务属性绑定到另一个服务属性。
麻烦的是,当我在视图中更改服务属性时,它们都没有更新。请问任何一个人可以放弃任何光吗?
这是一个掠夺者:http://plnkr.co/edit/D0YMzD?p=preview
控制器:
myApp.controller('Ctrl', ['$scope', 'serviceOne', function($scope, serviceOne) {
var ctrl = this;
ctrl.val = serviceOne.val;
$scope.$watch(function() {
return ctrl.val;
}, function() {
console.log('ctrl says val=' + ctrl.val);
}, true);
}]);
serviceOne:
myApp.service('serviceOne', ['serviceTwo', '$rootScope', function (serviceTwo, $rootScope) {
var sOne = this;
sOne.val = serviceTwo.val;
$rootScope.$watch(function() {
return sOne.val;
}, function() {
console.log('sOne says val=' + sOne.val);
}, true);
}]);
serviceTwo:
myApp.service('serviceTwo', ['$rootScope', function ($rootScope) {
var sTwo = this;
sTwo.val = "hello";
$rootScope.$watch(function() {
return sTwo.val;
}, function() {
console.log('sTwo says val=' + sTwo.val);
}, true);
}]);
答案 0 :(得分:2)
这是一个“模型中总是有一个点”的问题。你传递字符串,而不是对象引用。这有效:
var myApp = angular.module('myApp', []);
myApp.controller('Ctrl', ['$scope', 'serviceOne', function($scope, serviceOne) {
var ctrl = this;
ctrl.val = serviceOne.val;
$scope.$watch(function() {
return ctrl.val;
}, function() {
console.log('ctrl says val=' + ctrl.val.s);
}, true);
}]);
myApp.service('serviceOne', ['serviceTwo', '$rootScope', function (serviceTwo, $rootScope) {
var sOne = this;
sOne.val = serviceTwo.val;
$rootScope.$watch(function() {
return sOne.val.s;
}, function() {
console.log('sOne says val=' + sOne.val.s);
}, true);
}]);
myApp.service('serviceTwo', ['$rootScope', function ($rootScope) {
var sTwo = this;
sTwo.val = { s: "hello" };
$rootScope.$watch(function() {
return sTwo.val.s;
}, function() {
console.log('sTwo says val=' + sTwo.val.s);
}, true);
}]);
模板中的相应更改:
<div ng-controller="Ctrl as ctrl">
<input ng-model="ctrl.val.s"></input>
</div>