in a small Angular based application. I created two controllers and then want both the controllers to get data from a mysql database using a factory method. I can pass a set of records when I hard code them. but if I try to get those through http and/or using resource, I am not able to do that.
Most important... I am not sure what will be the best approach. Can you please help.
var myApp = angular.module('myApp', ['ngResource']);
myApp.factory('Data', function() {
var person = [
{name: "Mark Webber", sex: "Male", skills: "none", team: "webdev"},
{name: "Danny Web", sex: "Male", skills:"asdsad", team: "webdev"},
{name: "Steffy Graph", sex: "Female", skills:"ada", team: "accounts"},
{name: "Anna Martin", sex: "Female", skills:"asdsa", team: "webdev"}
];
return person;
});
function tricoreContrller($scope, Data, newData) {
$scope.users = Data;
console.log(Data);
}
function webdevController($scope, Data, newData) {
$scope.users = newData;
console.log(newData);
}
Both these controllers can interact with Data which is cool. But this is hard coded. I want the actual data coming from server which I want to come from ajax. How should I do this.
And also is there any particular advantage of using $resource, if yes any good tutorial? I tried the docs but didn't help much.
To keep it simple, use the $http module (see $http vs $resource). This has also the advantage that $http returns a promise which you should be able to use as follows (adapted from delaying-controller-initialization).
function tricoreContrller($scope, data) {
$scope.users = data;
}
function webdevController($scope, data) {
$scope.users = data;
}
var resolveFn = {
data : function($http) {
return $http({
method: 'GET',
url: 'http://server/getJSON'
});
}
};
tricoreContrller.resolve = resolveFn;
webdevController.resolve = resolveFn;
var myApp = angular.module('myApp', [], function($routeProvider) {
$routeProvider.when('/', {
templateUrl: '/editor-tpl.html',
controller: tricoreContrller,
resolve: tricoreContrller.resolve
});
// same for the other route for webdevController
});
Alternatively, if the two controllers are on the same route and one is contained in the other, it may be easier to access the parent controller's scope with $scope.$parent.data.