[英]pass the ng-model value to angular directive
我有一個場景,我有一定數量的文本框,當我點擊任何文本框時,其相應的ng模型將打印在瀏覽器控制台上。 我寫了以下角度代碼:
<html ng-app="myApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0-beta.0/angular.min.js"></script>
<script>
var app = angular.module("myApp", [])
app.controller("myAppCtrl", function($scope){
$scope.modelName = '';
});
app.directive("myDirective", function(){
return{
restrict: "A",
link: function(scope, elem, attrs){
scope.customFunc1 = function(){
console.log(attrs.ngModel);
scope.modelName = attrs.ngModel;
};
}
}
});
</script>
</head>
<body>
<div>
<input name="tb_1" type="text" ng-model="tb_1" ng-mousedown="customFunc1()" my-directive>
</div>
<div>
<input name="tb_2" type="text" ng-model="tb_2" ng-mousedown="customFunc1()" my-directive>
</div>
<div>
<input name="tb_3" type="text" ng-model="tb_3" ng-mousedown="customFunc1()" my-directive>
</div>
</body>
</html>
我有兩個問題:1)每當我點擊一個文本框時,就會打印第三個文本框的ng-model,而不管我實際點擊哪個文本框。 我該如何解決這個問題?
2)是否有更好的方法來完成上述要求?
問題是你的指令,它使用單一范圍。
為了解決您的問題,您需要通過提及scope: true
來使您的指令使用隔離范圍scope: true
指令內部以及更大的靈活性我建議您根據需要使用require: 'ngModel'
來ngModel
屬性,因為您的指令完全依賴於它。 通過創建字段,您可以在指令pre
/ post
鏈接功能中獲取ngModel
。 並且您可以隨時使用ng-model
變量值或驗證
指示
app.directive("myDirective", function() {
return {
restrict: "A",
require: 'ngModel',
scope: true,
link: function(scope, elem, attrs, ngModel) {
scope.customFunc1 = function() {
console.log(attrs.ngModel);
scope.modelName = attrs.ngModel;
};
}
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.