7

// template

      <div ng-controller="myController">
        <input type="text" ng-model="name">
        <p>{{name}}</p>
        <p>{{10+10}}</p>
        <button type="button" ng-click="{{myFunction()}}">click Me !!</button>

        <p ng-show="{{myFunction()}}">The name is {{ name | uppercase }}</p>

      </div>

// Controller

myApp.controller('myController', function ($scope) {

  $scope.name = 'Ranka';
  $scope.myFunction = function(){
    return true;
  };

});

Here it is failing in case of ng-click

angular.js:14525 Error: [$parse:syntax] Syntax Error: Token '{' invalid key at column 2 of the expression [{{myFunction()}}] starting at [{myFunction()}}].

Paul Floyd
  • 5,530
  • 5
  • 29
  • 43
  • 2
    Interpolation is not needed for ng-show and it is advised not to trigger events on ng-show, since it will increase your memory usage. Events should be triggered only on things like ng-click,ng-change etc... where you don't need any interpolation as all these are angular directives – Vivz Jul 13 '17 at 06:16
  • I think it's nice question if the question is related with two way binding in function. – Ramesh Rajendran Jul 13 '17 at 06:37

3 Answers3

0

Just use without the expression,

<button type="button" ng-click="myFunction()">click Me !!</button>
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
0

ng-show and ng-click are already an inbuild directive in angularjs. So, we no need to put it in curly braces for these expressions.

Without controller we doing the context in html itself. Use ng-init directive use to define as a variable you like and override the variable in ng-click as you want

<div ng-controller="MyCtrl" ng-init="showName = false;">
 <input type="text" ng-model="name">
        <p>{{name}}</p>
        <p>{{10+10}}</p>
        <button type="button" ng-click="showName = true">click Me !!</button>

        <p ng-show="showName">The name is {{ name | uppercase }}</p>
</div>

controller:

var myApp = angular.module('myApp',[]);

    function MyCtrl($scope) {
       $scope.name = 'Ranka';
    }

Working Fiddle

Arunkumar G
  • 126
  • 6
  • 1
    sorry but my question is why can't we add interpolation in expression if we are allowed to do it inside ng-show attribute? – Sourabh Jain 543 Jul 13 '17 at 06:37
  • For anything which we need one way binding we will use curly braces(interpolation). But for ng-show directive its by nature referring the model and hence not required interpolation over there. – Arunkumar G Jul 13 '17 at 08:40
0

try this simple way

    <button type="button" ng-click="{{ myFunction(); isShow = false}}">click Me !!</button>

    <p ng-show="{{isShow}}">The name is {{ name | uppercase }}</p>

and controller should be like,

var myApp = angular.module('myApp',[]);
       function MyCtrl($scope) {
       $scope.isShow= true;
       $scope.name = 'hallow world!';
    }
Ramesh Rajendran
  • 37,412
  • 45
  • 153
  • 234