5

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

greg-449
  • 109,219
  • 232
  • 102
  • 145
Odinn
  • 1,106
  • 9
  • 28
  • Please elaborate. What is the output you want? – Cruzer Dec 16 '16 at 10:02
  • y dont u follow the same way as u done for two? – Sa E Chowdary Dec 16 '16 at 10:03
  • @SaEChowdary that is why it is a doubt. – Mr_Perfect Dec 16 '16 at 10:05
  • Cruzer - it doesn't matter, I just want to manipulate with data like in directive two, which uses two-way binding – Odinn Dec 16 '16 at 10:07
  • 1
    @ Sa E Chowdary - 'couse it shows me 'undefined', and it says ''replace of undefined' . Please follow JsFiddle link and look at console – Odinn Dec 16 '16 at 10:09
  • 1
    okay got you....this is because the usage of @ and =,in case if @ your val not carrying to directive so you cant replace a undef and that's what your seeing console.http://stackoverflow.com/questions/14050195/what-is-the-difference-between-and-in-directive-scope-in-angularjs – Sa E Chowdary Dec 16 '16 at 10:19
  • you just need to use `attr.$observe` for accessing the value of one way binding,because its not connected with scope of parent . – Viplock Dec 16 '16 at 10:24
  • The value is not loading when you access the value through one-way binding in directive. So, it is showing `undefined`. – Sai M. Dec 16 '16 at 10:24

1 Answers1

2

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

Viplock
  • 3,259
  • 1
  • 23
  • 32