Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

angularjs

I'm trying to do some data manipulation using a one-way binding in my custom directive, but I receive "undefined" first time. What should I do with directive and not to use $watch ?

Example:

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

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,'')
      
      }
    }
  });

Example: JsFiddle

like image 768
Odinn Avatar asked Oct 30 '22 15:10

Odinn


1 Answers

You just need to use attr.$observe to access the value from one way binding change the code for link function to-

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 the update JsFiddle

like image 147
Viplock Avatar answered Nov 15 '22 09:11

Viplock