Angular - 无法读取属性' get'未定义的

时间:2015-04-24 16:55:05

标签: javascript angularjs

我想从某个网站获取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:无法读取属性&#39; get&#39;未定义的

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;
    });
  };

});

1 个答案:

答案 0 :(得分:4)

您不需要将服务和提供者注入函数本身,而是注入控制器:

function($http) { // Lose this !
  ....
}

然后将$http注入放在控制器声明中。