将 ng-model 值传递给 angular 指令

pass the ng-model value to angular directive

我有一个场景,我有一定数量的文本框,当我点击任何一个文本框时,它对应的 ng-model 将被打印在浏览器控制台上。我编写了以下 angular 代码:

<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 来使指令使用隔离范围,为了获得更大的灵活性,我建议您使用 [= 根据需要制作 ngModel 属性13=] 因为你的指令完全依赖于它。 通过使字段成为必需字段,您可以在指令 pre/post link 函数中获得 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;
      };
    }
  }
});

Working Plunkr