我想从某个网站获取JSON,然后使用此行代码将其显示在我的网站上
<div class="item" ng-style="{'margin': mb.itemMargin()}" ng-repeat="item in mb.getItems()"> {{mb.calculateItemMargin()}} </div>
在ma .js文件中,我正在使用此代码
mb.getItems = function($http){
return $http.get("http://SOME_URL")
.success(function(response) {
return response.dirs;
});
};
但是在控制台中,它显示此错误:
TypeError:无法读取未定义的属性“ get”
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)
我的angular.js文件
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;
});
};
});
最佳答案
您不需要将服务和提供程序注入到函数本身,而是注入到控制器:
function($http) { // Lose this !
....
}
并将
$http
注入放置在控制器声明中。关于javascript - Angular-无法读取未定义的属性“get”,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29853237/