Join the Stack Overflow Community
Stack Overflow is a community of 6.5 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

I have the following table based in this example (try to use the 'search' input)

<tr data-ng-repeat="product in filteredArray=(products | filter:findProducts)">
    <td>{{$index+1}}</td>
    <td>{{product.name}}</td>
    <td>{{product.price}}</td>
</tr>

As you can see, the filteredArray array is dynamic because this array will list objects based on the filter result and what I need to do is get this filteredArray array in the controller into a forEach method.

Controller

app.controller("controllerApp", function($scope){

  $scope.products = [
    {id:1, name: "product AAA", price: 12},
    {id:2, name: "product AAB", price: 21},
    {id:3, name: "product ABB", price: 32},
    {id:4, name: "product ABC", price: 45},
    {id:5, name: "product ACC", price: 34},
    {id:6, name: "product ACA", price: 63},
    {id:7, name: "product ACB", price: 47},
    {id:8, name: "product BBA", price: 87},
    {id:9, name: "product BBB", price: 59},
    {id:10, name: "product BBC", price: 43},
    {id:11, name: "product CCA", price: 76},
    {id:12, name: "product CCB", price: 44}
  ];

  // I can't get the 'filteredArray' from the view.
  angular.forEach(filteredArray, function(value, key){
    console.log("object from filtered array: "+value)
  })
});

Any idea?

share|improve this question

In the controller you should $watch for findProducts which is modified by ng-model. In the $watch handler you can update filteredArray. In the code that you wrote with forEach state will only run once on the controller initialization, and that's not what you want.

share|improve this answer
    
btw, in the controller you can inject $filter service and use it instead of implementing your own filter. – Sergey P. aka azure 21 hours ago

You should filter your collection before it is bound to your $scope.

See this SO question on how to use a filter in your controller. And the Angular documentation on how to use the built-in filter named 'filter.

app.controller("controllerApp", function($scope, $filter){
{
    var products = [...];
    $scope.filteredProducts = products;

    $scope.$watch('findProducts', function(newVal) {
        $scope.filteredProducts = $filter('filter')(products, newVal);

        angular.forEach($scope.filteredProducts, function(value, key){
            console.log("object from filtered array: "+value)
        });
    });
}

Then use the filteredProducts in your template

<input type="text" name="findProducts" data-ng-model="findProducts" placeholder="search" />

<tr data-ng-repeat="product in filteredProducts">
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.