2

I have an exemple as this one:

<div id="test" ng-repeat="foo">

I would like to change in my script the ng-repeat to something else (for example foo to foo2) when i do something (clicking on a button for example). Is it possible ?

Thank you a lot for your help !

0

2 Answers 2

2

I would like to change in my script the ng-repeat to something else (for example foo to foo2) when i do something (clicking on a button for example). Is it possible ?

Short Answer

No

AngularJS parses ng-repeat directive value and expects pattern item in collection

But you can replace list through which you iterate.

<div id="test" ng-repeat="item in foo()">

where foo() might be some method that returns array of objects

But is it possible to change the function foo() with foo2() dynamically ?

you can write method foo() as:

$scope.foo = function(){

   if($scope.clicked){
    return array1;
   }
   alse{
    return array2;
   } 
 }

Details

From Angular_6.6

var expression = $attr.ngRepeat;
      var ngRepeatEndComment = $compile.$$createComment('end ngRepeat', expression);

      var match = expression.match(/^\s*([\s\S]+?)\s+in\s+([\s\S]+?)(?:\s+as\s+([\s\S]+?))?(?:\s+track\s+by\s+([\s\S]+?))?\s*$/);

      if (!match) {
        throw ngRepeatMinErr('iexp', 'Expected expression in form of \'_item_ in _collection_[ track by _id_]\' but got \'{0}\'.',
            expression);
      }

The pattern is:

/^\s*([\s\S]+?)\s+in\s+([\s\S]+?)(?:\s+as\s+([\s\S]+?))?(?:\s+track\s+by\s+([\s\S]+?))?\s*$/
                  ^^^
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for your answer. But is it possible to change the function foo() with foo2() dynamically ? I have: " <div id="test" ng-repeat="item in foo()"> ", i click on a button and then i have " <div id="test" ng-repeat="item in foo2()"> " ?
@C.Norris on click you can change that foo() will return different list
@C.Norris you can also use ng-if to switch between 2 divs
1

You can repeat into foo and change it without problem when clicking on button. It's working using a third variable between your two arrays that you want to repeat.

Plunkr

<div ng-controller="ctrl">
  <div ng-repeat="x in choice">{{x}}</div>
  <button ng-click="switch()">Switch</button>
</div>

app.controller('ctrl',function($scope){
  $scope.items = [1,2,3,4,5];
  $scope.itemsAlternative = [6,7,8,9];

  $scope.choice = $scope.items;
    $scope.choice = ($scope.choice == $scope.items) ? $scope.itemsAlternative : $scope.items;
  }
})

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.