编辑:工作人员:http://plnkr.co/edit/iInh7TnbGvSHSPOWuWPk?p =preview
================================================== ==================
在下面的plunker中:http://plnkr.co/edit/TIfkYE?p = preview
一个非常简单的例子比较了工厂和服务的用法.双向数据绑定使用服务而不是工厂.为什么?
随着服务:
<button btn-radio="item.nb" ng-model="fromService.current>
Run Code Online (Sandbox Code Playgroud)
单击该按钮可正确更新服务的属性当前服务.
但是,使用工厂:
<button btn-radio="item.nb" ng-model="fromFactory.current>
Run Code Online (Sandbox Code Playgroud)
单击该按钮不会更新工厂的属性当前fromFactory.
我的用例如下:我想使用服务/工厂跨控制器和其他服务共享数据.
我读了很多参考资料,包括:
问题是var current一个原语,当你使用它作为一个值初始化对象时,它不会创建对初始变量的引用,对象属性只会获取它的值.
在您的isCurrent功能中,您将与原始变量进行比较,而原始变量永远不会发生变化.current但是,该属性由您创建的双向绑定更改ng-model
简单示例(可以在浏览器控制台中将其粘贴以确认):
var current=0;
var obj={
current: current
}
current=10;
alert(obj.current)// hasn't changed, is still 0
Run Code Online (Sandbox Code Playgroud)
要修复工厂,您需要与工厂返回的对象进行比较
myApp.factory('fromFactory', function() {
console.log("factory is called");
var current = 0;
return {
current: current,
isCurrent: function (nb) {
/* change return nb === current;*/
/* compare to the object version of "current" which is bound to ng-model*/
return nb === this.current;
},
printCurrent: function () {
console.log("print fromFactory", this.current);
}
};
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5634 次 |
| 最近记录: |