Search code examples
angularjsangularjs-scopeangularjs-ng-clicktwo-way-binding

Two way binding for ng-click directive in angularjs


I have calling a function in two elements. when I triggering the function an on-click event then also it should be hit once more time for wherever I called that function.

//html

<button type="button" ng-click="{{myFunction()}}">click Me !!</button>
  <p ng-show="{{myFunction()}}">{{name}}</p>

//controller

myApp.controller('myController', function ($scope) {
  $scope.name = 'Helow World!';
  $scope.myFunction = function(){
    return true;
  };
});

I also tried with "" instead of {{}} for two way binding

  <button type="button" ng-click="myFunction()">click Me !!</button>
  <p ng-show="myFunction()">{{name}}</p>

Problem :

The function will be firing only one time. Show my p tag does not show.

Solution

I can use a scope object to Show|hide the p tag. But that's not my question.

Question

My question is, how to implement Two way binding for event(ng-click) same as works like ng-repeat,ng-model,mg-show,etc in angularjs?


Solution

  • You're going about this wrong.

    The angular directives work with angular expressions, that means that whatever you insert into e.g. ng-show is executed using $parse(expr)($scope) - that's the short version. So if your expression contains a function call, that function is called whenever the directive decides to execute the expression. In the case of ng-show, that happens on every digest cycle. in the case of ng-click that happens on the click event.

    So when you use code like this: ng-show="myFunc()" and your function is defined like this:

    $scope.myFunc = function() { return true; };
    

    then on every digest, this function is executed and returns true to the ng-show. It doesn't have anything to do with what is going on in the ng-click directive.

    What you're asking can't be done. Angular just doesn't work that way. The solution you state with

    I can use a scope object to Show|hide the p tag. But that's not my question.

    is your best and only option.