I am very new to angularjs .I am stuck in getting local json data into controller
Here is .js file :
'use strict';
angular.module('angularPlaygroundApp').factory('campaignService', function($http) {
return $http.get('data/campaign.json');
})
.controller('CampaignCtrl', function ($scope, campaignService) {
$scope.name = '';
campaignService.success(function(data){
console.log('check');
$scope.name = data.compaigns;
console.log(data);
});
});
Even console.log inside controller not giving response .
Let me know if I am making some mistake .
You can see my directory structure here
You need to create an object inside your factory declaration and return that.
angular.module('angularPlaygroundApp').factory('campaignService', function($http) {
var fact = {};
fact.getData = function() {
return $http.get('data/campaign.json');
};
return fact;
})
Inside your controller, you'd use
campaignService.getData()....
Here's the entire code (you had an error in the module decrlaration also):
campaign.json (copied some array code off wikipedia):
{
"campaigns":
[
{ "type": "home", "number": "212 555-1234" },
{ "type": "office", "number": "646 555-4567" }
]
}
index.html:
<!doctype html>
<html lang="en" ng-app="angularPlaygroundApp">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body >
<script src= "angular.js"></script>
<script src= "script.js"></script>
<div ng-controller='CampaignCtrl'>
{{name}}
</div>
</body>
</html>
script.js:
angular.module('angularPlaygroundApp', [])
.factory('campaignService', function($http) {
var fact = {};
fact.getData = function() {
return $http.get('data/campaign.json');
};
return fact;
})
.controller('CampaignCtrl', function ($scope, campaignService) {
$scope.name = [];
campaignService.getData()
.success(function(data){
$scope.name = data.campaigns;
console.log(data);
})
.error(function(data) {
console.log('error');
});
});