I am trying to get data from my server from an ajax request in my Angularjs controller then access the data through another javascript file. I am using canvas and trying to grab stored data on the database through my angularjs controller.
I store the data in a global scope variable in my angularjs controller and I am trying to access it through my canvas javascript file.
I know you can access the controller methods like this:
var scope = angular.element($('#Controller')).scope();
scope.$apply(function(){
scope.getFunc();
});
However whenever I try and access a global scope variable it returns in this object called [remove: function] and I do not know how to get the data from this object.
Is there a better way to get the global scope variables from Angularjs? Thanks for the help.
-
consider using a service, and inject it wherever it is going to be used. this way you can share data between your components.akonsu– akonsu2014年07月21日 12:00:40 +00:00Commented Jul 21, 2014 at 12:00
-
first of all your canvas javascript file must be brought part of the angular framework, best option is probably to turn it into a directive. Then, when you are using your directive under a controllers scope, it can access all controller exposed variables.Heikki– Heikki2014年07月21日 19:34:06 +00:00Commented Jul 21, 2014 at 19:34
1 Answer 1
This is a plunker that shows how to share data between controllers. I am linking the plunker here.
A service is a singleton object where you can store and retrieve data across controllers. This is generally the preferred way to share data.
http://plnkr.co/edit/bsFxDn3RQCGlmZLJMAil?p=preview
Code of the service
fasterApp.service('fasterService', function($rootScope){
var serv = {
name: '', age: '', place: '', gender: '',
addData: function (n, a, p, g) {
this.name = n;
this.age = a;
this.place = p;
this.gender = g;
$rootScope.$broadcast('dataAdded');
}
};
return serv;
})
Add data is called when data is to be added.
The following code goes in the second controller
$scope.$on('dataAdded', function () {
$scope.name = fasterService.name;
$scope.age = fasterService.age;
$scope.place = fasterService.place;
$scope.gender = fasterService.gender;
});
and the dataAdded event is recieved in the second controller after data is added.
Comments
Explore related questions
See similar questions with these tags.