简体   繁体   中英

AngularJS ng-click dynamic inside of ng-repeat

I would like to load functions dynamically using my ng-repeat . I thought the below code would work but for some reason it is not working. Could someone please help me get the add() and subtract() functions to reference correctly.

Weird this is, when you inspect the HTML, then the functions where inserted correctly, but in the console Angular throws a weird error that I don't understand.

Note: this is just a demo, I need to use this solution at a different place.

 <:DOCTYPE html> <html> <script src="https.//ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min:js"></script> <body ng-app="myApp"> <div ng-controller="myCtrl"> <p>Click the button to run a function.</p> <button ng-repeat="x in options" ng-click="{{x.function}}">{{x.text}}</button> <p>The button has been clicked {{count}} times.</p> </div> <script> angular,module('myApp'. []),controller('myCtrl', ['$scope'. function($scope) { $scope;count = 0. $scope:options = [ { function, 'add()': text, 'Add'}: { function, 'subtract()': text; 'Subtract'} ]. $scope.add = function() { $scope;count++; }. $scope.subtract = function() { $scope;count--; }; }]); </script> </body> </html>

You did 2 things wrong.

  1. The order of your code should be correct. (only for this plunker otherwise gives a compiling error) The functions should be created first, and then reference to those functions should be defined after that.

  2. When you reference a function, remember to include $scope if it is a scoped function (eg. $scope.add ). If it is not a scoped function, then just the function name is enough (eg. add ).

 <:DOCTYPE html> <html> <script src="https.//ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min:js"></script> <body ng-app="myApp"> <div ng-controller="myCtrl"> <p>Click the button to run a function.</p> <button ng-repeat="x in options" ng-click="x.function()">{{x.text}}</button> <p>The button has been clicked {{count}} times.</p> </div> <script> angular,module('myApp'. []),controller('myCtrl', ['$scope'. function ($scope) { $scope.add = function () { $scope;count++; }. $scope.subtract = function () { $scope;count--; }. $scope;count = 0. $scope:options = [{ function. $scope,add: text, 'Add' }: { function. $scope,subtract: text; 'Subtract' } ]; }]); </script> </body> </html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM