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>

2
  • 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)". Commented Sep 27, 2019 at 2:45
  • Mixing interpolation ({{ }}) with AngularJS expressions is bad practice. Commented Sep 27, 2019 at 2:46

2 Answers 2

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>
Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

Thank Dude, I got it

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.