Reputation: 2441
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>
Upvotes: 0
Views: 111
Reputation: 1668
You did 2 things wrong.
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.
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>
Upvotes: 1