SpacePope SpacePope - 3 months ago 19
Javascript Question

Angular click event not working, what gives?

I'm building a silly little calculator in an attempt to learn AngularJS. I'm attempting to use ng-click trigger events to update the "screen" of my calculator. Here's my code:



var calcApp = angular.module('NodeCalc', []);
calcApp.controller('CalcController', ['$scope', function ($scope) {
$scope.memory = {
recall: function() {
console.log('memory recall');
},
clear: function() {
console.log('memory clear');
},
add: function(value) {
console.log('memory add');
}
}
$scope.buttons = {
memory: [
{text: 'mrc', action: $scope.memory.recall},
{text: 'm-', action: $scope.memory.clear},
{text: 'm+', action: $scope.memory.add},
]
};
}]);

<body ng-app="NodeCalc" ng-controller="CalcController">
<form class="calc">
<p class="calc-display">
<input type="text" name="res" id="res" value="0" class="calc-display-input" onfocus="this.blur()">
</p>
<p class="calc-row">
<button ng-repeat="button in buttons.memory" type="button" class="calc-button calc-button-gray" ng-click="{{button.action}}">{{button.text}}</button>
<button type="button" class="calc-button calc-button-red calc-button-big" onclick="a('/')">/</button>
</p>





So, I know it has to do with the way I'm attaching my memory functions to my scope object. Can I not use scope in this way on the ng-click directive? I'm not really sure how else to achieve my goal here. The buttons render correctly, but I get a huge angular error-barf in my console related to:


Error: [$parse:syntax] http://errors.angularjs.org/1.5.8/$parse/syntax?p0=%7B&p1=invalid%20key&p2=2&p3=%7B%7Bbutton.action%7D%7D&p4=%7Bbutton.action%7D%7D

Answer

ng-click expression should be ng-click="button.action()"

var calcApp = angular.module('NodeCalc', []);
calcApp.controller('CalcController', ['$scope',
  function($scope) {

    $scope.memory = {
      recall: function() {
        console.log('memory recall');
      },
      clear: function() {
        console.log('memory clear');
      },
      add: function(value) {
        console.log('memory add');
      }
    }
    $scope.buttons = {
      memory: [{
        text: 'mrc',
        action: $scope.memory.recall
      }, {
        text: 'm-',
        action: $scope.memory.clear
      }, {
        text: 'm+',
        action: $scope.memory.add
      }, ]
    };
  }
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<body ng-app="NodeCalc" ng-controller="CalcController">
  <form class="calc">
    <p class="calc-display">
      <input type="text" name="res" id="res" value="0" class="calc-display-input" onfocus="this.blur()">
    </p>
    <p class="calc-row">
      <button ng-repeat="button in buttons.memory" type="button" class="calc-button calc-button-gray" ng-click="button.action()">{{button.text}}</button>
      <button type="button" class="calc-button calc-button-red calc-button-big" onclick="alert('/')">/</button>
    </p>