我正在尝试在我的应用程序中存储某种全局变量。我读到,最好是使用值而不是服务或rootscope。
因此,我创建了此代码段以测试值的行为。值似乎在控制器内部发生了变化,但是如果我在另一个控制器中使用该值,则该变化似乎丢失了。有没有一种方法可以在运行时更改值,为什么更改不能持久化?
这是我在jsfiddle上的代码
Java脚本
var myApp = angular.module('myApp',[]);
myApp.value("basePath", "");
myApp.controller('TestController', function($scope, basePath) {
$scope.preEdit = basePath;
basePath = window.location.href;
$scope.postEdit = basePath;
});
myApp.controller('SampleController', function($scope, basePath) {
$scope.transferedValue = basePath;
})
HTML:
<div ng-controller="TestController">
Before Editing: {{preEdit}}<br>
After Editing: {{postEdit}}<br>
</div>
<div ng-controller="SampleController">
In another Controller: {{transferedValue}}
</div>
您将在此条目中找到答案:AngularJS中的全局变量
将值定义为对象
myApp.value("basePath", {value: ""});
之后,您可以更改basePath.value
控制器。
myApp.controller('TestController', function($scope, basePath) {
$scope.preEdit = basePath.value;
basePath.value = window.location.href;
$scope.postEdit = basePath.value;
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句