如何从嵌套元素中获取指令中的ng-model值?

时间:2016-01-19 13:06:47

标签: angularjs

如何在嵌套HTML元素的link-function中获取ngModel的值,即:

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

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

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

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

2 个答案:

答案 0 :(得分:0)

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

您可以使用scopeDOM获取ngModel值,以便在link函数

中访问它

答案 1 :(得分:0)

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

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