angularjs .service无法在控制器之间传递variables
我已经创build了一个服务来传递控制器之间的布尔标志。 服务看起来像这样:
angular.module('MyApp') .service('sharedProperties', function () { var flag = false; return { getProperty: function () { return flag; }, setProperty: function(value) { flag = value; } }; });
首先设置标志的控制器是这个
angular.module('MyApp') .controller('test1', function($scope, $location, $http, $window, sharedProperties) { $scope.flag1 = function () { if ($location.path() == '/') { sharedProperties.setProperty(false); return false; }else { sharedProperties.setProperty(true); return true; }; }; });
而接收参数的控制器是这样的
angular.module('MyApp') .controller('test2', function($scope, $location, $http, $window, sharedProperties) { $scope.flag2 = sharedProperties.getProperty(); });
test1中的flag1采用正确的值,但test2始终为false。 如果我将服务中的标志初始化为true,那么在test2中总是如此。 如果我不初始化它 – 它在test2中是未定义的。
这种行为是完全预期的,并没有特别的链接到angularjs,它的工作原理就像在香草的JavaScript。 您遇到的问题是由于JavaScript基元是通过值而不是通过引用传递的事实。 您可以在这里阅读更多关于它的信息: JavaScript是传递引用还是传值语言?
如何解决你的代码? 使用一个将通过引用传递的对象。
你可以试试这个:
angular.module('MyApp') .service('sharedProperties', function () { var flag = { value: false }; return { getProperty: function () { return flag; }, setProperty: function(value) { flag.value = value; } }; }); angular.module('MyApp') .controller('test1', function($scope, $location, $http, $window, sharedProperties) { $scope.flag1 = function () { if ($location.path() == '/') { sharedProperties.setProperty(false); return false; }else { sharedProperties.setProperty(true); return true; }; }; }); angular.module('MyApp') .controller('test2', function($scope, $location, $http, $window, sharedProperties) { $scope.flag2 = sharedProperties.getProperty(); // use flag2.value in your markup });
原因是我相信Angular在添加到控制器时用new
初始化服务。
所以当在test1中操作时,其在该控制器中的服务的实例不在另一个控制器中共享。 我可能是错误的,但会build议首先使用this.flag
而不是var flag
。 另外,你的test2控制器会在angular度加载时进行调用,呈现false
但不会监视变化。
创build一个JSBIN为你解决它: http ://jsbin.com/xoqup/1/edit