Reputation: 145
I can return an object, but not the object property. Why? I have tried many things but nothing seems to work. Sorry but I'm new in Angular
app.factory('myData', function() {
var data = {
product: ''
};
function addItem(value) {
data.product = value;
}
function getList() {
return data.product;
}
return {
addItem: addItem,
getList: getList
};
});
Updated with the controllers functions
function controllerA(myData){
var scope = this;
scope.total = 0;
scope.addMore = function(){
scope.total++;
myData.addItem(scope.total);
}
}
function controllerB(myData){
var scope = this;
scope.total = 0;
scope.total = myData.getList();
}
Upvotes: 0
Views: 105
Reputation: 692191
The total in controller B is initialized when the controller is instantiated.
The total in controller A is modified when addMore()
is called. So if you call addMore()
after controller B is instantiated, controller B will always reference the original value ot the total: the empty string:
t0: controller A is instantiated
t1: controller B is instantiated. B.total is initialized with the result of myData.getList(), which is the empty string:
data.product -------\
|
V
B.total -------> empty string
t2: a.addMore() is called. That modifies the service's total, but not the variable in B
data.product ---> 1
B.total -------> empty string
If you reference the object itself in the controller, you don't have this problem, because B has a reference to data, and data.product is modified by A.
Upvotes: 1
Reputation: 420
You can read good article:
demo.factory(
"Friend",
function( trim ) {
// Define the constructor function.
function Friend( firstName, lastName ) {
this.firstName = trim( firstName || "" );
this.lastName = trim( lastName || "" );
}
// Define the "instance" methods using the prototype
// and standard prototypal inheritance.
Friend.prototype = {
getFirstName: function() {
return( this.firstName );
},
getFullName: function() {
return( this.firstName + " " + this.lastName );
}
};
// Define the "class" / "static" methods. These are
// utility methods on the class itself; they do not
// have access to the "this" reference.
Friend.fromFullName = function( fullName ) {
var parts = trim( fullName || "" ).split( /\s+/gi );
return(
new Friend(
parts[ 0 ],
parts.splice( 0, 1 ) && parts.join( " " )
)
);
};
// Return constructor - this is what defines the actual
// injectable in the DI framework.
return( Friend );
}
);
Upvotes: 0