我有以下工厂可行。但我想向工厂添加数据,我不知道如何做到这一点..
感谢您的帮助!
app.factory('Favorites', function($http, $q){
var factory = {
artists : false,
getArtists : function(){
var deferred = $q.defer();
if(factory.artists !== false){
console.log('true');
deferred.resolve(factory.artists);
}else{
console.log('false');
$http.get('https://homechefhome.fr/rise/favorites-artists.php?user_id=10155092792384782')
.success(function(data, status){
// if everything is good, we save data in factory
factory.artists = data;
console.log('L55', factory.artists, status);
deferred.resolve(factory.artists);
}).error(function(data, status){
deferred.reject('No data collected');
console.log('L59', data, status);
});
}
return deferred.promise;
}
};
return factory;
});
答案 0 :(得分:0)
如果您希望将数据“添加”到您的应用程序,则必须在控制器中引用工厂和getArtists功能。这样的事情可以解决问题:
angular.module('myApp', [])
.controller('MainCtrl', function($scope, $http, Artists) {
$scope.artists = Artists.getArtists();
console.log($scope.artists);
});
如果那不是你想要的,请告诉我,我会修改我的答案。
答案 1 :(得分:0)
典型地,
添加以下行:factory.artists.push({myobj:'helloworld'}); 我实际上可以添加对象,但我想从视图/控制器中执行此操作。
$http.get('https://homechefhome.fr/rise/favorites-artists.php?user_id=10155092792384782')
.success(function(data, status){
// if everything is good, we save data in factory
factory.artists = data;
factory.artists.push({myobj:'helloworld'});//add an object, I want to do that from a controller, another view
console.log('ligne 55',factory.artists, status);
deferred.resolve(factory.artists);
}).error(function(data, status){
deferred.reject('No data collected');
console.log('ligne 59', data, status);
});
这是来自控制器的代码:(它不起作用)
$scope.addFavoriteArtist = function(){
Favorites.getArtists().then(function(){
Favorites.factory.push({hello:'Controller'});
});
};
它说:无法读取未定义的属性“推送”