serge
serge

Reputation: 15239

Filter in angular ng-init

I try to initialise a collection in the ng-init. Why this code does not work?

<div ng-app="myApp" ng-controller="PeopleCtrl">
  <ul ng-init="myPeople=(people|filter:{show:true})" ng-repeat="person in myPeople">
    <li>{{person.name}}, {{person.show}}
  </ul>
</div>

CodePen

I don't need using ng-if or other things, I just wonder if possible to initialise a collection using a filter in ng-init

Upvotes: 0

Views: 1584

Answers (3)

Stepan Kasyanenko
Stepan Kasyanenko

Reputation: 3186

Because you write your ng-init on element, that repeated you ng-init code run every time for new tag. To avoid this write ng-init somewhere else.

Like this

var myApp = angular.module('myApp', []);

myApp.controller('PeopleCtrl', function($scope, $window) {


  $scope.people = ([{
    id: 17,
    name: "Peter",
    age: 21,
    show: true
  }, {
    id: 07,
    name: "David",
    age: 20,
    show: false
  }, {
    id: 37,
    name: "Anil",
    age: 22,
    show: true
  }, {
    id: 45,
    name: "Anil",
    age: 19,
    show: false
  }]);
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="PeopleCtrl" ng-init="myPeople=(people|filter:{show:true})">
  <ul ng-repeat="person in myPeople">
    <li>{{person.name}}, {{person.show}}
  </ul>
</div>

Upvotes: 0

Pankaj Parkar
Pankaj Parkar

Reputation: 136174

ng-init would not work when data is coming asynchronously, and I don't think so ng-init suits your case.

I'd suggest you to use alias for filtered data in ng-repeat itself, while filtering myPeople collection

ng-repeat="person in people|filter:{show:true} as myPeople"

Upvotes: 2

Hardik Vaghani
Hardik Vaghani

Reputation: 2173

Yes you can initialize filter in ng-init like

ng-init="FilteredGeojson = (ho | filter:search)"

Regards.

Upvotes: 0

Related Questions