我想使用我的 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>
最佳答案
你做错了两件事。
您的代码顺序应该正确。 (仅限此插件,否则会出现编译错误)应首先创建函数,然后定义对这些函数的引用。
引用函数时,如果它是作用域函数,请记住包含
$scope
(例如$scope.add
)。如果它不是作用域函数,那么只需函数名称就足够了(例如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>
关于javascript - AngularJS ng-click 动态在 ng-repeat 内部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61498909/