Reputation: 1152
I want to get JSON from some website and then display it on my website using this line of code
<div class="item" ng-style="{'margin': mb.itemMargin()}" ng-repeat="item in mb.getItems()"> {{mb.calculateItemMargin()}} </div>
In ma .js file I'm using this code
mb.getItems = function($http){
return $http.get("http://SOME_URL")
.success(function(response) {
return response.dirs;
});
};
But in console it shows this error:
TypeError: Cannot read property 'get' of undefined
at mb.getItems (angular.js:56) at ib.functionCall (angular.js:12404) at Object.<anonymous> (angular.js:12910) at n.$get.n.$digest (angular.js:14300) at n.$get.n.$apply (angular.js:14571) at angular.js:1455 at Object.e [as invoke] (angular.js:4203) at d (angular.js:1453) at uc (angular.js:1473) at Jd (angular.js:1367)
My angular.js file
var app = angular.module('mediaBrowserApp', []);
app.controller('mediaBrowser', function($http){
var mb = this;
mb.showMainPage = function (){
if(mb.currentDir.length>0){
return false;
}
else{
return true;
}
};
var dirToRedir = '';
mb.dirContent = function(dir){
mb.currentDir = dir;
};
mb.nextDir = function(){
return dirToRedir;
};
mb.calculateItemMargin = function(){
var minWidth = 145;
var minMargin = 17;
var minElementWidth = minWidth + minMargin;
var numOfItemsFitInContainer = 0;
var widthOfParent = document.getElementById('mb-container').clientWidth;
for(i=widthOfParent; i>minElementWidth; i = i-minElementWidth ){
numOfItemsFitInContainer++;
}
var spaceLeft = widthOfParent - (minElementWidth * numOfItemsFitInContainer);
if(spaceLeft>numOfItemsFitInContainer){
var newItemMargin = minMargin + (spaceLeft/numOfItemsFitInContainer);
}
else{
var newItemMargin = minMargin;
}
newItemMargin = newItemMargin / 2;
return Math.floor(newItemMargin);
};
mb.itemMargin = function(){
var width = mb.calculateItemMargin() + "px";
return width;
};
mb.getItems = function($http){
return $http.get("http://SOME_URL")
.success(function(response) {
return response.dirs;
});
};
});
Upvotes: 0
Views: 1179
Reputation: 17064
You don't need to inject services and providers to the functions themselves, but rather to the controller:
function($http) { // Lose this !
....
}
And place the $http
injection in the controller declaration instead.
Upvotes: 4