wilson
wilson

Reputation: 657

AngularJS: Get dynamic array from filter then use it into a forEach method

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?

Upvotes: 0

Views: 205

Answers (2)

seangwright
seangwright

Reputation: 18195

You should use $scope.$watch to filter your products in your controller based on user input. You'll then have access to that filtered dataset to perform your .forEach loop.

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">

Upvotes: 1

Sergey P. aka azure
Sergey P. aka azure

Reputation: 4722

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.

Upvotes: 1

Related Questions