AngularJS: read initial value of ngModel.$viewValue from different directive

后端 未结 4 1929
南笙
南笙 2021-01-03 08:44

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

# coffee script
app.directive \'directive\', -> 
  return {
      requ         


        
相关标签:
4条回答
  • 2021-01-03 09:24

    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.

    0 讨论(0)
  • 2021-01-03 09:28

    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

    0 讨论(0)
  • 2021-01-03 09:36

    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);
                }
    
    0 讨论(0)
  • 2021-01-03 09:44

    I just fixed it myself... stupid :)

        link: (scope, element, attrs, ngModelCtrl) ->
    
            scope.$watch(ngModelCtrl, ->
              console.log(ngModelCtrl.$viewValue)
            )
    

    does work! yippieh!

    0 讨论(0)
提交回复
热议问题