0

I am trying to do .replace within the template inside of the directive

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

i wan to do replace(/'/g, '"') on the {{data.Title}}

any suggestions?

Tony
  • 474
  • 1
  • 7
  • 19

2 Answers2

0

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");
        }
      }
    };
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="docsSimpleDirective">
  <div ng-controller="Controller">
    <div my-customer></div>
  </div>
</div>
VivaLaPanda
  • 809
  • 7
  • 24
0

I think the best way is using a filter.

You can create you filter like:

angular.module('myApp', [])
.filter('myReplace', function() {
  return function(input) {
    var out = ... //your replace logic
    return 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.

Alex Mufatti
  • 41
  • 1
  • 3