Skip to content Skip to sidebar Skip to footer

Angular Template .replace

I am trying to do .replace within the template inside of the directive directive('sampleComponent', function () { return { template: '

{{data.

Solution 1:

I think the best way is using a filter.

You can create you filter like:

angular.module('myApp', [])
.filter('myReplace', function() {
  returnfunction(input) {
    var out = ... //your replace logicreturn out;
  };
});

And then apply it to your template:

directive('sampleComponent', function () {
  return {
    template: '<h2 style="border:1px solid red">{{data.Title | myReplace}}</h2>'
  };
})

Remember to inject the filter in your directive controller.

Solution 2:

In Angular to modify variables in the template we manipulate them in scope. In either the directive's link function or the relevant controller, simply call $scope.data.Title.replace(/'/g, '"'); (The link function would probably be the best place - Link vs compile vs controller).

angular.module('docsSimpleDirective', [])
  .controller('Controller', ['$scope', function($scope) {

  }])
  .directive('myCustomer', function() {
    return {
      template: 'Name: {{customer.name}} Address: {{customer.address}} <a ng-click="replace()" href="#">clickme</a>',
      link: function($scope) {
        $scope.customer = {
          name: 'Naomi',
          address: '1600 Amphitheatre'
        };
        
        $scope.replace = function() {
          console.log("running");
          $scope.customer.name = $scope.customer.name.replace(/a/g, "o");
        }
      }
    };
  });
<scriptsrc="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script><divng-app="docsSimpleDirective"><divng-controller="Controller"><divmy-customer></div></div></div>

Post a Comment for "Angular Template .replace"