0

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?

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

btw, in the controller you can inject $filter service and use it instead of implementing your own filter.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.