Reputation: 27
I'm doing some work with angular factories and in one instance I want the factory to reference some of its own data but it doesnt seem to be working. In the example below data2 needs to read the value from testVariable but it doesn't seem to work. In the example below the data is just empty. In my more complex scenario I am using the value as a Boolean to show/hide a value and get the error "Unable to get property 'xxxxxx' of undefined or null reference". Does anyone know how I could successfully reference testVariable as needed below. One thing to note is that it needs to be returned inside of factory as there is a $watch set up to do some actions if the value changes.
Thanks.
(function() {
angular.module('myApp.Module').factory(
'MyFactory',
function() {
var factory = {
testVariable : 'testData2',
randomData : [
{
data1: 'testData1',
data2: testVariable,
data3: 'testData3'
}, {
data4 : 'testData4',
data5 : 'testData5',
data6 : 'testData6',
}
}
return factory;
});
}());
Upvotes: 0
Views: 68
Reputation: 17603
Like you did it, testVariable
is an object property, not a variable! You need to define the variable outside the factory
object.
(function() {
angular.module('myApp.Module').factory('MyFactory',function() {
var testVariable = 'testData2';
var factory = {
randomData : [
{
data1: 'testData1',
data2: testVariable,
data3: 'testData3'
}, {
data4 : 'testData4',
data5 : 'testData5',
data6 : 'testData6',
}
}
return factory;
});
}());
Upvotes: 2