Pascal Berger
Pascal Berger

Reputation: 4342

Using angular filter with string parameter in ng-click

I've a custom angular filter directive which can replace strings using the following syntax:

{{ 'MyValue' | replace: 'My':'Foo' }}

This works fine. Now I want to use this filter inside a ng-click

<button ng-click="alert('{{ 'MyValue' | replace: 'My':'Value'}}')">Click Me!</button>

This throws an parse exception (I assume because of the surrounding apostrophes from the alert). What's the correct syntax in this case?

A Plunkr is available here: http://plnkr.co/edit/xEGjY40LWORt5nlaJq46

Upvotes: 0

Views: 983

Answers (2)

Kalhan.Toress
Kalhan.Toress

Reputation: 21901

here is the working Plunker

i added the controller and call a function inside controller when ng-click fired

 <body ng-app="MyApp" ng-controller="x">
   <p>{{ -3 | replace: '-':'n' }}</p>
   <p>
     <button ng-click="x('MyValue','replace','My','Value')">Click Me!</button>
  </p>
 </body>

in script.js

myApp.controller('x', function($scope, $filter) {
  $scope.x = function(input,filterName,replaceStr,replaceBy) {
      var filtered = $filter(filterName)(input,replaceStr,replaceBy);
      alert(filtered);      
  }
});

for the more

ng-click='alert("1111")' dose not work because the when u put something inside ng-click, alert() in this case, it will check for $scope.alert so, alertis not work insideng-click`

Upvotes: 1

Oleg Belousov
Oleg Belousov

Reputation: 10121

As a rule, you cannot use interpolated values as a parameter to an executable attribute in angular ('&').

what you need to do is:

markup:

<button ng-click="alert(customValue)">Click Me!</button>

Controller code

$scope.customValue = $fitler('replace')('MyValue', 'My', 'Value');

Upvotes: 1

Related Questions