我试图将值从一个模块传递给angularjs中的另一个模块。 使用.value工作正常。
工作: -
var app = angular.module('app', []);
app.value('movieTitle', 'The Matrix');
var app1 =angular.module('app1', ['app']);
app1.controller('MyController', function (movieTitle) {
//Here I am getting value. which is working fine.
console.log(movieTitle)
})
不工作: -
var app = angular.module('app', []);
app.value('movieTitle', 'The Matrix');
app.controller('MyController', function (movieTitle) {
//Here I override the value.
movieTitle = "The Matrix Reloaded";
})
var app1 =angular.module('app1', ['app']);
app1.controller('MyController', function (movieTitle) {
//Here I am getting old value not update value.
console.log(movieTitle)
})
在第二个示例中,我尝试更新其更新的值。但是当Am访问其他模块的值时,它只显示旧值未更新,任何人都可以帮助我。我错了......
答案 0 :(得分:1)
JavaScript字符串是不可变的,因此您无法更新注入的值(因为它是一个字符串) - 您只是更改注入变量的内容。您可以采用另一种方法来包含对象中的字符串,现在您可以更新对象中的字符串:
var movie = { title: 'The Matrix' };
angular.module('app', [])
.value('movie', movie)
.controller('MyController', function (movie) {
//Here I override the value.
movie.title = "The Matrix Reloaded";
});
angular.module('app1', ['app'])
.controller('MyController', function (movie) {
console.log(movie.title);
});
答案 1 :(得分:0)
该值基本上是string
,它是原始类型且没有引用,因此该值被绑定一次。
我已经与工厂签订了fiddle并将其用于模块间应用程序作为您的要求
var app = angular.module('myApp', []);
var app1 = angular.module('myApp1', ['myApp']);
app.controller('HelloCtrl', HelloCtrl);
app.controller('GoodbyeCtrl', GoodbyeCtrl);
app1.controller('ctrl2', ctrl2);
app.factory('testFactory', function(){
var _name = 'hello';
return {
getName: function(text){
return _name;
},
setName: function(name){
_name = name;
}
}
});
function HelloCtrl($scope, testFactory){
$scope.name = testFactory.getName();
testFactory.setName('hello2');
}
function GoodbyeCtrl($scope, testFactory){
$scope.name = testFactory.getName();
testFactory.setName('hello3');
}
function ctrl2($scope, testFactory){
$scope.name = testFactory.getName();
}
希望它有所帮助。