更改服务.js中的变量值

Change var value in Service.js

本文关键字:变量值 js 服务      更新时间:2023-09-26

我正在使用Ionic制作移动应用程序。我将"蓝色"存储为初始值。现在我想更改服务中的值。

.factory('repository', function() {
      var theme="button-calm";
      setTheme: function(input){
         theme=input; 
      },
      getTheme: function(){
         return theme;
     }

但我不知道为什么主题不能改变。

工厂的语法似乎有点不对劲,请确保工厂返回一个 javascript 对象:

app.factory('repository', function() {
  var theme="button-calm";
  return {
    setTheme: function(input){
       theme = input; 
    },
    getTheme: function(){
       return theme;
    }
  }
});

接下来将工厂注入控制器

app.controller('SomeController', ['repository', function(repository) {
...

然后,您可以在控制器中设置/获取主题:

repository.getTheme();
repository.setTheme('changed value');

有关工作示例,请参阅此PLNKR:http://plnkr.co/edit/T6OoL10QzCK6hoX1HZc8?p=preview

请尝试使用此服务:

(function(){
service('repositoryService', function(){
    var service = {
        theme : "button-calm";
        getTheme : function(){
            return this.theme; 
        },
        setTheme : function(input){
            this.theme = input; 
        }
    };
    return service; 
});
})();

显然,您需要在控制器中引用repositoryService,就像您需要引用repository一样。