How to format data in a directive using one-way binding?

I try to do some data manipulation using the one-way binding in my custom directive, but first I get "undefined". What should I do with the directive and not use $ watch?

Example:

<one val={{arr[1].value}}> </one>
<two val="arr[0].value"> </two>
Run codeHide result

directives:

 .directive('one', function(){
    return {
      restrict: 'E',
      scope: {
      val:'@'
      },
      template: '<div> 1111 {{val}} </div>' ,
      link: function (scope) {
      console.log('scope', scope.val) // SHOWS UNDEFINED BUT INSERT DATA IN TEMPLATE
      if(scope.val) scope.val =	scope.val.replace(/\d/g,'')
      
      
      }
    }
  })
    .directive('two', function(){
    return {
      restrict: 'E',
      scope: {
      val:'='
      },
      template: '<div> 2222 {{val}} </div>' ,
       link: function (scope) {
      console.log('scope', scope.val)
      scope.val = 	scope.val.replace(/\d/g,'')
      
      }
    }
  });
Run codeHide result

Example: JsFiddle

+4
source share
1 answer

You just need to use attr.$observeto access the value from one of the methods of binding code changes for the link function in

link: function (scope,elum,attr) {
  attr.$observe('val', function(value) { console.log('scope', scope.val) })
  //console.log('scope', scope.val)
  if(scope.val) scope.val = scope.val.replace(/\d/g,'')


  }

Find JsFiddle Update

+2
source

Source: https://habr.com/ru/post/1663939/


All Articles