fourth fourth - 1 month ago 7
AngularJS Question

Is my service definition right in angular?

(function(){
angular.module('myApp',[])
})();

(function(){
angular.module('myApp.dashboard',[])
})();

(function(){
angular.module('myApp.value',[])
})();

(function(){
'use strict';
angular.module('myApp.value').service('whichToShow',function(){
alert("running2");
var logged=true;
return {
getVar: function(){
return logged;
},
setVar: function(value){
logged=value;
}

};
});
})();

(function(){
'use strict';
angular.module('myApp.dashboard').controller('mainControl',mainControl);

mainControl.$inject = ['whichToShow'];
alert("running1");
function mainControl(whichToShow){
this.logged=whichToShow.getVar();
alert(this.logged);

};
})();


I am writing one app imitating another finished app, but I can't use my new defined service. I am writing according to his code https://github.com/PatrickO10/meetUp/blob/master/js/all.js
Could you tell me which part should I modify? You had better change on my code, so that I can know why mine is wrong. Thanks!

you can see all my code here:
https://plnkr.co/edit/YeahrG28bT2izX8gMKor?p=preview
I haven't done much about that, what I want now is to make some buttons invisible

Answer

What you wrote is a factory. To define a service, you have to get the instance and enrich it with methods.

So, you can change your service into a factory like this :

(function(){
    'use strict';
    angular.module('myApp.value').factory('whichToShow',function(){
        alert("running2");
        var logged=true;
        return {
            getVar: function(){
                return logged;
            },
            setVar: function(value){
                logged=value;
            }

        };
    });
})();

Or, define your service like this:

(function(){
    'use strict';
    angular.module('myApp.value').service('whichToShow',function(){

        var logged=true;
        this.getVar = function(){
                return logged;
            };
        this.setVar =function(value){
                logged=value;
            };
    });
})();

Edit 1:

Your plunker code is not correct. Please, check this correction : https://plnkr.co/edit/2HAwy7MV4dK0yUuBcCfG?p=preview

  • Your inclusion of all.js was pointing to js/all.js instead of just all.js.

  • In your mainControl, Your injection wasn't correct.

Comments