C.Norris
C.Norris

Reputation: 97

Angularjs modify dynamically ng element in HTML

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 !

Upvotes: 2

Views: 67

Answers (2)

Maxim Shoustin
Maxim Shoustin

Reputation: 77904

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*$/
                  ^^^

Upvotes: 2

Zooly
Zooly

Reputation: 4787

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;
  }
})

Upvotes: 1

Related Questions