1

I was trying to make a few buttons using Array. The buttons displayed, but the function from the array is not working.

var module = angular.module('app',[]);
module.controller('Ctrl',['$scope', function ($scope){
  $scope.data = [
  {link: "myNav.pushPage('page1')", btn:'Page 1'},
  {link: "myNav.pushPage('page2')", btn:'Page 2'},
  {link: "myNav.pushPage('page3')", btn:'Page 3'}
  ]
}])
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="app" ng-controller="Ctrl">
  <tr ng-repeat="x in data">
    <td><button ng-click="{{x.link}}">{{x.btn}}</button></td>
  </tr>
</div>
Firdaus
  • 33
  • 5
  • 2
    `ng-click` accepts expressions, so you don't need the interpolation syntax (i.e. `{{ ... }}`). Instead you can use `$eval` as part of the expression: `ng-click="$eval(x.link)"`. – miqh Sep 27 '19 at 02:45
  • Mixing interpolation (`{{ }}`) with AngularJS expressions is [bad practice](https://stackoverflow.com/questions/51592045/why-mixing-interpolation-and-expressions-is-bad-practice). – georgeawg Sep 27 '19 at 02:46

2 Answers2

0

If the function is always the same and only the parameter changes, you can have the parameter in data array and pass it like this:

<table>
    <tr ng-repeat="x in data">
        <td><button ng-click="test(x.link)">{{x.btn}}</button></td>
    </tr>
</table>

With this array:

$scope.data = [{
  link: "page1",
  btn: 'Page 1'
},
{
  link: "page2",
  btn: 'Page 2'
},
{
  link: "page3",
  btn: 'Page 3'
}]

Check a working demo: DEMO

Bill P
  • 3,622
  • 10
  • 20
  • 32
0
var module = angular.module('app',[]);
module.controller('Ctrl',['$scope', function ($scope){
    $scope.data = [
      {link: "page1", btn:'Page 1'},
      {link: "page2", btn:'Page 2'},
      {link: "page3", btn:'Page 3'}
    ]
    $scope.navigate(link){
    //$state.go(link) //navigate page
}

}]);

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="app" ng-controller="Ctrl">
  <tr ng-repeat="x in data">
    <td><button ng-click="navigate(x.link)">{{x.btn}}</button></td>
  </tr>
</div>
siva kumar
  • 569
  • 1
  • 3
  • 13