簡體   English   中英

AngularJS ng-click 在 ng-repeat 中動態

[英]AngularJS ng-click dynamic inside of ng-repeat

我想使用我的ng-repeat動態加載函數。 我認為下面的代碼會起作用,但由於某種原因它不起作用。 有人可以幫我正確引用add()subtract()函數。

奇怪的是,當您檢查 HTML 時,正確插入的功能,但在控制台中 Angular 會拋出一個我不明白的奇怪錯誤。

注意:這只是一個演示,我需要在不同的地方使用這個解決方案。

 <: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>

你做錯了兩件事。

  1. 您的代碼順序應該是正確的。 (僅針對此 plunker,否則會產生編譯錯誤)應首先創建函數,然后再定義對這些函數的引用。

  2. 當您引用 function 時,如果它是一個作用域 function(例如$scope.add ),請記住包含$scope 如果它不是作用域 function,那么只需 function 名稱就足夠了(例如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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM