AngularJS Noob:如何从“init”调用控制器中的函数?

时间:2014-07-29 20:45:11

标签: angularjs

我试图保持干燥,所以我将重复的代码移动到我的控制器中的一个函数中,但它现在说该函数未定义:Error: setFilterChoices is not defined

app.controller('MensCtrl', ['$scope', "MensEyeglass", "MensSunglass", "Color", "Shape", "Material", function($scope, MensEyeglass, MensSunglass, Color, Shape, Material) {

  $scope.init = function(category) {
    $scope.colors = [];
    $scope.shapes = [];
    $scope.materials = [];

    switch (category) {
    case "Eyeglasses":
      $scope.products = MensEyeglass.query({}, setFilterChoices(data));
      break;
    case "Sunglasses":
      $scope.products = MensSunglass.query({}, setFilterChoices(data));
      break;
    }
  }


  //it's defined here isn't it??
  $scope.setFilterChoices = function(data) {
    for (var i = 0; i < data.length; i++) {
      var product = data[i];

      if ($scope.shapes.indexOf(product.shape) == -1) {
        $scope.shapes.push(product.shape);
      }

      if ($scope.materials.indexOf(product.material) == -1) {
        $scope.materials.push(product.material);
      }


      for (var j = 0; j < product.products_colors.length; j++) {
        var product_color =  product.products_colors[j];
        if ($scope.colors.indexOf(product_color.color) == -1) {
          $scope.colors.push(product_color.color);
        }
      }
    }
  }

我也错过了函数(数据)回调。这是答案:

  $scope.products = MensSunglass.query({}, function(data) {
    $scope.setFilterChoices(data);
  });

1 个答案:

答案 0 :(得分:3)

它在范围内,所以当你调用它时使用$scope.setFilterChoices(data)