简体   繁体   English

将ng-model值传递给angular指令

[英]pass the ng-model value to angular directive

I have a scenario where I have certain number of text-boxes and when I click on any of the text-box, its corresponding ng-model is to be printed on the browser console. 我有一个场景,我有一定数量的文本框,当我点击任何文本框时,其相应的ng模型将打印在浏览器控制台上。 I have written the following angular code: 我写了以下角度代码:

<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>

I have two questions: 1) Whenever I click on a text-box the ng-model of the third text-box is printed, irrespective which text-box I actually click. 我有两个问题:1)每当我点击一个文本框时,就会打印第三个文本框的ng-model,而不管我实际点击哪个文本框。 How do i fix that? 我该如何解决这个问题?

2) Is there a better way of accomplishing the above requirement? 2)是否有更好的方法来完成上述要求?

The problem is your directive, It is using single scope. 问题是你的指令,它使用单一范围。

For solving your problem you need to make your directive to use isolated scope by mentioning scope: true inside directive & for more flexibility I'd suggest you to make ngModel attribute as required using require: 'ngModel' as you directive is fully dependant on it. 为了解决您的问题,您需要通过提及scope: true来使您的指令使用隔离范围scope: true指令内部以及更大的灵活性我建议您根据需要使用require: 'ngModel'ngModel属性,因为您的指令完全依赖于它。 By making field required you can get ngModel inside directive pre / post link function. 通过创建字段,您可以在指令pre / post链接功能中获取ngModel and you can played with ng-model variable value or validation anytime 并且您可以随时使用ng-model变量值或验证

Directive 指示

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;
      };
    }
  }
});

Working Plunkr 工作Plunkr

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM