My goal is to consolidate all of my model functionality in one centralized location. I want the ability to access its methods from within the model itself:
JavaScript
/**
* This application displays "OK" a specified number of times based on the button pressed
*/
angular.module('myApp', [])
.controller('MyCtrl', ['$scope', function MyCtrl($scope) {
$scope.okModel = {
oks: [],
addOne: function(){
this.oks.push(["OK"]);
},
addTwo: function(){
this.addOK();
this.addOK();
},
buttons: [
{name:"addOK", action: this.addOne}, // The issue may lie here
{name:"add2OKs", action: this.addTwo}
]
};
}]);
HTML
<div ng-controller="MyCtrl">
<!-- display the object containing all the "OK"s -->
oks: {{okModel.oks}}
<!-- render the buttons -->
<button ng-repeat="item in okModel.buttons" ng-click="item.action()">
{{item.name}}
</button>
<!-- display the "OK"s -->
<div ng-repeat="ok in okModel.oks">
{{ok[0]}}
</div>
</div>
While no errors are thrown, the functionality is not working as expected. The "OK"s are not being added to the model. The root of the problem seems to stem from the okModel.buttons
action property.
Here's a plunker showcasing the issue: https://plnkr.co/edit/mDk43yEKSQB37QSmiKJn?p=preview
TL;DR: It appears that the problem lies with this
in buttons
, what alternative approach should I consider?
Extra question: Being new to Angular, I understand that I might not be utilizing models in the most effective manner. If you have suggestions for a more efficient model implementation, I would appreciate any advice.