角集中的变量访问任何范围 [英] angular set a variable accessible to any scope

查看:145
本文介绍了角集中的变量访问任何范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创造与角度的应用程序。有在该应用为用户输入的字符串的形式。当用户输入一个字符串,这就要求使用功能NG-提交:

I am creating an app with Angular. There is a form in the app for a user to enter a string. When a user enters a string this calls a function using ng-submit:

ng-model="input1" ng-submit="update()"

在更新功能,我可以使用,然后访问输入1的值

Within the update function I can then access the value of input1 using

$scope.input1

我想要做的是使该值成为更新功能的只是范围的可访问的外部,以便它可以由角应用内任何其他被调用。

What I would like to do is allow that value to be accessible outside of just the scope of the update function, so that it can be called by anything else within the angular app.

在理想情况下,我希望能够更新thing1:

Ideally, I would like to be able to update thing1:

var app = angular.module('app1, []);
var thing1 = "value from input"

我经历过的文档和我想也许我需要做的是设置一个app.value,所以:

I've been through the documentation and am thinking maybe what I need to do is set an app.value, so:

var app = angular.module('app1, []);
app.value('thing1', "value from input")

然后在提交功能设置thing1的值,使其更新app.value,但是这是行不通的。

Then in the submit function set the value of thing1 so that it updates the app.value, but that isn't working.

我不知道我怎么能做到这一点。有什么想法?

I'm not sure how I can do this. Any thoughts?

推荐答案

如果有人有兴趣,我创建了一个服务如下:

If anyone is interested, I created a service as follows:

app.service('thing', function(){
var string1 = '123'
return{
 getString: function(){
  return string1;
  }
 setString: function(value){
 string1 = value;
}

然后在控制器内添加我的东西服务:

Then within the controller I add the thing service:

app.controller('myController', function(thing){
controller code
});

我可以通过把一个值到东西服务从任何范围:

I can put a value into the 'thing' service from any scope by using:

thing.setString($scope.valueIwantToSet)

,或通过从任何范围值:

Or get a value from any scope by using:

$scope.variableIwantToUse = thing.getString();

这篇关于角集中的变量访问任何范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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