I'm blocked on this problem since a couple of hours, so any help is much appreciated.
i've a controller, in which i defined a variable (an empty array):
function MainCtrl(scope, graph) {
scope.myVar = [];
graph.send("a", "b");
}
MainCtrl.$inject = ['$scope', 'plotData'];
plotData
is a custom service i wrote. It use $http
to query a database, and retrieve the data I need.
angular.module('myApp.services', []).
factory('plotData', ['$http', function(async) {
var mainScope = angular.element("#main").scope();
return {
send: function(plotType, plotDetail) {
var thisObj = this;
var ajaxConfiguration = {
method: 'POST',
url: '******************',
data: {
type: plotType,
detail: plotDetail
}
};
async(ajaxConfiguration).
success(function(data, status, headers, config) {
mainScope.myVar = data.plot;
/*
data.plot is what i expected!
I also try with: return data.plot;
*/
}).
error(function(data, status, headers, config) {
console.info("error");
});
},
doSomething: function(data) { },
doSomethingElse: function() { }
};
}]);
The problem is that in the controller scope.myVar
doesn't change.
Basically what i'm trying to do is update a variable defined in the controller from a directive.
What I'm doing wrong?
UPDATE:
@dogoku: As i know i don't need to use $apply because i'm using $http that is still in Angular.
@Mark Rajcok:
0) No, i'm using the real $http service:
factory('plotData', ['$http', function(async) {
/* service */
}]);
1) yes, i wrote in the code comment. data.plot is what I expected it to be. The backend code works great, so I've not posted it.
2) I will try your link and let you know.
Meanwhile any help is still welcome.
As mentioned in the comments, getting the scope via a selector then calling scope() is not very Angular. A better way would be to return a promise from the service. Pete has a good example of how do to this here: https://stackoverflow.com/a/12513509/215945
angular.copy()
should be used instead of assignment in the success() callback, so that the data-binding is not lost in the controller.