Javascript 使用服务变量
我已经在指令中注入了一个服务,有没有办法在指令中共享服务中的数据 就像我有一个名为Javascript 使用服务变量,javascript,angularjs,Javascript,Angularjs,我已经在指令中注入了一个服务,有没有办法在指令中共享服务中的数据 就像我有一个名为resultsDirective的指令一样,一些名为dataService的服务已经被注入(在我进行的过程中进行了补充)。是否有一种方法可以从指令中的服务访问变量?为了实现某些功能: angular.module("someModule").service("dataService", function() { var shareVariable; }) angular.module("someModul
resultsDirective
的指令一样,一些名为dataService
的服务已经被注入(在我进行的过程中进行了补充)。是否有一种方法可以从指令中的服务访问变量?为了实现某些功能:
angular.module("someModule").service("dataService", function() {
var shareVariable;
})
angular.module("someModule").directive("resultsDirective" , ["dataService", function(dataService) {
return {
restrict: ,
scope: ,
link: function() {}
//sorry about the lack of implementation here, just made something skeletal
}
}])
因此,如果我只想
console.log
在resultsDirective
中的shareVariable
,我将如何访问该数据?我确信在Angular中有一个简单的方法?这不是一个真正的角度问题,这是一个javascript问题。无法访问作用域之外的本地作用域变量。您必须通过这样做来公开sharedVariable
angular.module("someModule").service("dataService", function() {
this.shareVariable = null;
});
(function () {
var app = angular.module('myApp', []);
app.service("dataService", function () {
this.shareVariable = 'shohel';
});
app.directive("resultsDirective", ["dataService", function (dataService) {
return {
restrict: 'E',
scope: {},
link: function (scope, ele, att) {
var svc = dataService.shareVariable;
}
};
}]);
})();
首先,记住服务是单例的,所以在服务中修改一个变量将对您的所有应用程序产生影响。你现在面临的问题是你不知道什么是闭包,我建议你考虑一下 如何解决这个问题?两种选择:
- 返回具有属性的对象(不推荐,可能会变得混乱)
- 创建一个getter/setter功能
var myModule = angular.module('myModule' []);
myModule.factoy('service', function () {
var myVariable;
return {
getMyVariable: function () { return myVariable; },
setMyVariable: function (newVal) { myVariable = newVal; }
}
});
实际上你可以做的更多,但我不知道你需要什么
此外,您的服务也无法正常工作,请查看:对于使用工厂的@donnanicolas服务,您不会返回任何内容。他正在使用服务。