【问题标题】:How to get the ng-model value inside a directive from a nested element?如何从嵌套元素获取指令内的 ng-model 值?
【发布时间】:2016-01-19 13:06:46
【问题描述】:

如何在嵌套 HTML 元素的链接函数中获取 ngModel 的值,即:

<div myattr>
 <label>Title</label>
 <input type="text" ng-model="need.value.of.this">
</div>

'myattr' 必须保留在顶部 div 元素内。

那么,在链接函数中获取'need.value.of.this' 的值的方法是什么?通常我会使用'required: ngModel',然后使用带有$viewValue 的ngModelCtrl。有没有办法在链接函数中获取输入的ngModelCtrl

app.directive('myattr', [
function () {
    return {
        restrict: 'EA',
        link: function ($scope, $element, $attrs) { 
            // need ng-model value from input
        }
    }
}
}

【问题讨论】:

  • 你可以在 myattr 上注册 ng-model,类似 ng-model 将自己注册到 ng-form 元素

标签: angularjs


【解决方案1】:
app.directive('myattr', [
function () {
    return {
        restrict: 'EA',
        scope: {
           ngModel: '=',
        },
        link: function ($scope, $element, $attrs) { 
            // need ng-model value from input
        }
    }
  }
}

您可以使用scope 从您的DOM 获取ngModel 值,以便在您的link 函数中访问它

【讨论】:

    【解决方案2】:

    您可以将观察者添加到您的范围

    link: function ($scope, $element, $attrs) { 
       $scope.$watch('need.value.of.this', function(newValue) {
          // do something with new value
       });
    }
    

    【讨论】:

    • 嗨,我的 ng-model 可能会有所不同......在“need.value.of.this”上放置一个观察者对我来说太具体了,使用 ngModel.$viewValue 我解决了这个问题...... . 但是现在我有嵌套元素并且 ngModel 是未定义的)......任何解决方案?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多