我正在尝试通过工厂链接两个控制器。我想在一个控制器中将一个指针设置为工厂的值myFactoryVar
,这样当工厂中的值发生变化时,控制器中的值controllerVar
会发生变化。
我已经阅读过这篇文章,其中有几篇喜欢AngularJS : The correct way of binding to a service properties
但我似乎无法使用我的代码。也许这是格式?也许我绑定到一个没有意义的原始类型。这是我到目前为止所知,如何让它按预期工作?
控制器1:
;(function() {
'use strict';
angular
.module('myapp')
.controller('MyCtrl1', MyCtrl1);
function MyCtrl1(myTracker) {
var vm = this;
angular.extend(vm, {
controllerVar: myTracker.myFactoryVar,
myTrackerVarIncrement: myTrackerVarIncrement
});
function myTrackerVarIncrement() {
myTracker.myFactoryVarIncrement();
/* should log the same value as myFactoryVar but doesn't */
console.log(vm.controllerVar);
}
}
})();
控制器2:
;(function() {
'use strict';
angular
.module('myapp')
.controller('MyCtrl2', MyCtrl2);
function MyCtrl2(myTracker) {
var vm = this;
angular.extend(vm, {
myTrackerVarIncrement: myTrackerVarIncrement
});
function myTrackerVarIncrement() {
/* I want to be able to increment the value in the factory, */
/* and by means of that, the value in the other controller too */
myTracker.myFactoryVarIncrement();
}
}
})();
厂:
;(function() {
'use strict';
angular
.module('myapp')
.factory('myTracker', myTracker);
function myTracker() {
var factory = {
myFactoryVar: 1,
myFactoryVarIncrement: myFactoryVarIncrement
};
return factory;
function myFactoryVarIncrement() {
factory.myFactoryVar += 1;
}
}
})();
答案 0 :(得分:0)
也许我在没有意义的情况下绑定到原始类型。
myFactoryVar
是对象的属性。分享它作为财产的对象的引用。
;(function() {
'use strict';
angular
.module('myapp')
.controller('MyCtrl1', MyCtrl1);
function MyCtrl1(myTracker) {
var vm = this;
angular.extend(vm, {
//controllerVar: myTracker.myFactoryVar,
controllerRef: myTracker,
myTrackerVarIncrement: myTrackerVarIncrement
});
function myTrackerVarIncrement() {
myTracker.myFactoryVarIncrement();
/* should log the same value as myFactoryVar but doesn't */
//console.log(vm.controllerVar);
console.log(vm.controllerRef.myFactoryVar);
}
}
})();
绑定到引用以共享内容。