Here is my temp.js
angular.module('temp', [])
.service('tempFactory', function() {
this.a =10;
});
and here is my temp.Spec.js
describe('temp', function() {
var tempFactory;
beforeEach(function() {
var mockedTempFactory = {};
module('temp', function($provide) {
$provide.value('tempFactory', mockedTempFactory);
});
mockedTempFactory.a = 20;
inject(function(_tempFactory_) {
tempFactory = _tempFactory_;
});
});
it('console.log of a property', function() {
console.log(tempFactory.a);
});
});
In console I get value of 20.
But if I define tempFactory like this:
angular.module('temp', [])
.constant('tempFactory', {
a: 10;
});
In console I get value of 10.
Why can't I redefine tempFactory which was initially defined as constant, but can redefine tempFactory which was initially defined as service, value or factory?
Because when you create a service, you provide a constructor function to it
Angular then creates an instance of this function kinda like this:
and returns back exactly that instance, so you could access the
a
property right away.But the constant does not do anything, it just returnes what you've passed to it, so
will just return a function back to you. If you want to be able to access the property
a
in this situation, then you have to "instantiate" it:See the plunker.
You can read more about the behavior of different provider in the documentation.