3

I would like to read the initial value ngModel.$viewValue from different directive.

# coffee script
app.directive 'directive', -> 
  return {
      require: '?ngModel',
      link: (scope, element, attrs, ngModelCtrl) ->
      ........
           console.log(ngModelCtrl.$viewValue) # does give NaN!

           ngModelCtrl.$setViewValue('something'); # only after setting reading does work
           console.log(ngModelCtrl.$viewValue)

I really appreciate any help.

BKM
  • 6,949
  • 7
  • 30
  • 45
sp33c
  • 494
  • 1
  • 5
  • 15

4 Answers4

7

I just fixed it myself... stupid :)

    link: (scope, element, attrs, ngModelCtrl) ->

        scope.$watch(ngModelCtrl, ->
          console.log(ngModelCtrl.$viewValue)
        )

does work! yippieh!

sp33c
  • 494
  • 1
  • 5
  • 15
2

No need to watch and ng-init is bad. Something like..

      return {
          require: 'ngModel',
          link: function(scope, element, attrs, ngModel) {
                var getter = $parse(attrs.ngModel);
                var value = getter(scope);

           }
        };

Here value will give the initial bound value in model.

Bibin
  • 434
  • 2
  • 5
  • 20
1

put your actions within a $timeout... like what you do with $apply, so your code will run after $digest finished it's process...

like this:

link: function (scope, el, attr, ctrl) { //Ctrl will bind to required ones
                //ctrl[0] -> ngModel
                $timeout(function() {
                    scope.parentId = ctrl[0].$viewValue;
                    scope.startUp();
                }, 0);
            }
Hassan Faghihi
  • 1,888
  • 1
  • 37
  • 55
0

If you want to work with some value from HTML inside your directive you should use ngInit. It will look like

<div directive ng-init="variable='value'"></div>

I faced the same problem, and it turned out that what I was doing was not an Angular way. Check this link for more details

Community
  • 1
  • 1
n-canter
  • 268
  • 1
  • 11