bigpotato
bigpotato

Reputation: 27527

AngularJS Noob: How to call functions in controller from "init"?

I'm trying to keep things DRY so I moved my repetitive code into a function in my controller, but it's now saying that the function is undefined: 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);
        }
      }
    }
  }

I was missing the function(data) callback as well. Here's the answer:

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

Upvotes: 0

Views: 55

Answers (1)

Ben Wilde
Ben Wilde

Reputation: 5672

its on the scope so use $scope.setFilterChoices(data) when u call it.

Upvotes: 3

Related Questions