角度存储值,用于在多个页面上进行访问 [英] Angular store value to service to acces on multiple pages

查看:188
本文介绍了角度存储值,用于在多个页面上进行访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

解决方案:我可以在更新变量'something'之前调用我的.get()函数,因此它没有显示更新的变量。

SOLUTION: It seemed that my .get() function invoked before I could update the variable 'something' and therefore it didn't show the updated variable.

当我在真实页面上测试时,它就像一个魅力:)

When I tested it on the real page it worked like a charm :)

final FIDDLE

final FIDDLE

注意:我确实添加了返回设置功能立即更新视图。

note: I did add a return to the set function to immediately update the view.

更新:让我的工厂正常工作但不能获取绑定到工厂.set()函数的值。 FIDDLE

UPDATE: got my factory working alright but can't get the value bound to the factory .set() function. FIDDLE

我正在构建一个安装USB网络连接器的手册,需要存储一些变量来显示多个页面中的正确内容(在同一个控制器中很难)。

I’m building a manual to install a USB-network connector and need to store some variables to show the right content across multiple pages (within the same controller tough).

在做了一些研究之后,似乎'服务'是正确的方法,但我不能让它们工作。

After doing some research it seems 'services' are the right way to do this however I can't get them to work.

它确实有用我把这个函数放在控制器本身里面但是当我改变页面时它又被重置为'[]'。

It does work when I put the function inside the controller itself but it get's reset to '[]' again when I change page.

控制器里面的函数我现在拥有它是:

function inside controller as I have it right now is:

$scope.isActiveSystem = [];

$scope.activeSystem = function(name) {
    $scope.isActiveSystem = name.value;
}

有人能指出我正确的方向如何将其放入服务或给我一个学习的例子,这样我就可以更好地理解发生了什么?

Can someone point me in the right direction how to put this inside a service or give me an example to study so I can understand better what's going on?

另外,我应该将数据存储在工厂还是某些服务中?

Also, should I store my data in a factory or some service?

我尝试提供服务: FIDDLE

推荐答案

你离解决方案不远。

说真的,我曾经尝试过记住服务和工厂之间的区别。最后,两者都可以完全以相同的方式使用,以满足相同的要求。

Seriously, I used to try to remember the difference between service and factory. In the end, both can be used exactly in the same way, to fulfill the same requirement.

app.factory('dmFactory', function() {
//name.value should equal to system.value from the controller 
var somethingIWantToRemember = {};
return {
   set: set,
   get: get
}

function get(key){      //You can forget about the key if you want
    return somethingIWantToRemember[key];
}

function set(key, value){
    somethingIWantToRemember[key] = value;
}

});

在您的控制器中,您只需要以这种方式调用这两个函数:

and in your controller, you just have to call both functions that way :

$scope.something = dmFactory.get(key);

dmFactory.set(key, $scope.something);

这篇关于角度存储值,用于在多个页面上进行访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆