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?

2 Answers 2

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.

2
  • thank you so for my replace(/'/g, '"') I will just add var out = replace(/'/g, '"');
    – Tony
    Jun 9, 2017 at 21:59
  • something like var out = input.replace(/'/g, '"'); Jun 9, 2017 at 22:08
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>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.