角度:工厂模型中的更新未反映在控制器中

编程入门 行业动态 更新时间:2024-10-25 14:31:06
本文介绍了角度:工厂模型中的更新未反映在控制器中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个保存用户首选项值的用户首选项工厂.页面加载时为空.用户登录后,将用用户个人资料填充. 伪代码

I have a user preference factory that holds user preference values. When the page loads it is empty. After user logs in it is filled up with user profile. pseudo code

app.factory('pref', function($rootScope){ var pref = {}, age, name; $rootScope.$on('logged.in', function(){ pref.name = 'sam'; pref.age = 30; pref.currency = '$'; age = getAge(); name = getName(); }) function getName(){ //format name return name; } function getAge(){ return age; } return { currency: pref.currency, age: age, name: name } })

然后我将工厂注入控制器中:

Then I inject the factory in my controller:

app.controller('MainCtrl', function($scope, pref) { $scope.name = pref.name; //Return undefined var currency = pref.currency; $scope.price = function(amount){ return amount + currency; //don't show $ sign } });

首选工厂中的返回值未在控制器中更新.我该如何运作?

Return value from pref factory not updating in controller. How do I make it work?

plunkr plnkr.co/edit/SKJC5hUPEm72JqGJyT9y

推荐答案

从pref工厂返回的对象,

{ setPreference: setPreference, currency: pref.currency, name: pref.name, formatTime: formatTime }

将currency和name分配给未定义的属性.由于undefined不是引用类型,因此currency和name不会看到"对象pref的任何更新.

assigns currency and name to undefined properties. Since undefined is not a reference type, currency and name will not "see" any updates to object pref.

我建议将引用pref对象的属性作为工厂返回的对象的一部分:

I suggest instead that a property that references the pref object be part of the object returned by the factory:

{ setPreference: setPreference, prefs: pref, formatTime: formatTime }

现在,我们对pref所做的任何更新都将反映在prefs中.在您的控制器中,请参考该对象的属性,如下所示:

Now, any updates we make to pref will be reflected in prefs. Refer to properties of that object as follows in your controller:

console.log(prefService.prefs.name)

为了不更改pref指向的引用,请使用angular.copy()修改pref引用的对象:

In order to not change the reference that pref points to, use angular.copy() to modify the object that pref references:

function setPreference(values){ //pref = values; <<-- won't work, since pref will now reference another object angular.copy(values,pref); }

更新:要使视图在name更改时自动更新,建议将对prefs的引用保存为范围属性:

Update: to have the view automatically update when the name changes, I suggest saving a reference to prefs as a scope property:

$scope.prefs = prefService.prefs;

然后在视图/HTML中使用{{prefs.name}}:

Then use {{prefs.name}} in the view/HTML:

<p>Hello {{prefs.name}}!</p>

更新后的 朋克车

Updated plunker

更多推荐

角度:工厂模型中的更新未反映在控制器中

本文发布于:2023-11-10 06:34:12,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1574620.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:模型   器中   角度   工厂

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!