0

I have created a component in AngularJS for reusable buttons. I need to pass button text into a function argument via ng-click event of the same button. However, I am unable to get the button text in a function call.

Any help would be much appreciated.

Below is my code.

Index.html

<div class="object-actions" ng-repeat="val in value">
   <button-control  ng-repeat="v in val" name="{{v}}"></button-control>
</div>

Component

(function() {
  "use strict";
  angular
    .module("buttonCtrl", [])
    .component("buttonControl", {
      template: `<button ng-click="getName('$ctrl.name')">{{$ctrl.name}}</button>`,
      controller: buttonCtrl,
      bindings: {
        name: "@"
      }
    });

  buttonCtrl.$inject = ["$scope"];

  function buttonCtrl($scope) {
    $scope.getName = function(name) {
      alert(name);
    };
  }
})();

Output enter image description here

1 Answer 1

1

The problem is that you pass the variable with quotes and it becomes a string.

ERRONEOUS

ng-click="getName('$ctrl.name')"

However you don't need to pass it into the function in order to print it, and also there is no need to inject $scope:

function buttonCtrl() {
    var ctrl = this;

    ctrl.getName = function() {
      alert(ctrl.name);
    };
}

BETTER

ng-click="$ctrl.getName()"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.