控制器之间的值的变化并不持久

时间:2016-07-04 13:23:44

标签: javascript angularjs

我试图在我的应用程序中存储某种全局变量。我读到最佳做法是使用值而不是服务或rootcope 所以我创建了这段代码片段来测试值的行为。似乎控制器的值会改变,但如果我在另一个控制器中使用该值,则更改似乎会丢失。 有没有办法在运行时更改值,为什么更改不会持久?

Here是我在jsfiddle上的代码

的Javascript

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>

4 个答案:

答案 0 :(得分:4)

您可以在此条目中找到答案:Global variables in AngularJS

将值定义为Object

JavaSparkContext

之后,您可以更改控制器中的myApp.value("basePath", {value: ""});

basePath.value

答案 1 :(得分:1)

使用常量

myApp.constant( 'basePath', '' );

这将允许您将值注入模块。

答案 2 :(得分:0)

这是一个代码片段:

var app = angular.module('app', []);

app.controller('TestController', function($scope, $rootScope) {
  $rootScope.postEdit = window.location.href;
});

app.controller('SampleController', function($scope, $rootScope) {
  $scope.transferedValue = $rootScope.postEdit;
});
<!DOCTYPE html>
<html ng-app="app">

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script>
</head>
<body>
  <div ng-controller="TestController" ng-bind="postEdit"></div>
  <div ng-controller="SampleController" ng-bind="transferedValue"></div>
  </div>
</body>
</html>

答案 3 :(得分:-1)

hai JohnDizzle,

   You Can Pass the Data from One Controller to Anthor Controller Using BroadCast . And You can Store The LocalStorage And Retrive In Anthor Controll ALSO .. If Have Any Doughts Ask me.