Я могу вернуть объект, но не свойство объекта. Зачем? Я пробовал много вещей, но ничего не работает. Извините, но я новичок в Angular
app.factory('myData', function() {
var data = {
product: ''
};
function addItem(value) {
data.product = value;
}
function getList() {
return data.product;
}
return {
addItem: addItem,
getList: getList
};
});
Обновлено с помощью функций контроллеров
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();
}
Общее количество в контроллере B инициализируется при создании экземпляра контроллера.
Общее количество в контроллере A изменяется при addMore()
. Поэтому, если вы вызываете addMore()
после создания экземпляра контроллера B, контроллер B всегда будет ссылаться на исходное значение ot: пустая строка:
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 total, but not the variable in B
data.product ---> 1
B.total -------> empty string
Если вы ссылаетесь на сам объект в контроллере, у вас нет этой проблемы, потому что B имеет ссылку на данные, а data.product изменен A.
Вы можете прочитать хорошую статью:
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 );
}
);
getList()
вы получаетеundefined
или''
?