在自定义指令中未定义的 NG 模型值打印

ng model value printing undefined inside the custom directive

本文关键字:NG 模型 打印 未定义 自定义 指令      更新时间:2023-09-26

我创建一个自定义指令,该指令采用一个简单的模板,包括输入类型文本区域,我将ng模型分配给ngmodel并在此创建一个链接函数,我创建一个更改事件,我试图获取ngmodel值,但其打印未定义,请帮助我解决此问题,在这里发布我尝试过的链接,如果需要,请进行更正普伦克尔,代码从这里开始

// Code goes here
var app = angular.module('myApp',[]);
app.directive('markdownEditor', function () {
  return {
    restrict: 'E',
    scope: {
      ngModel: "="
    },
    require:'ngModel', 
    template:
    '<textarea ng-model="ngModel"></textarea>' +
    '{{ ngModel}}',
    link:function(scope,ele,attr,ctrl){
      ele.on("keydown",function(){
        alert(scope.ctrl)
      })
    }
  }
});
app.controller('DemoCtrl', function ($scope) {
  var x= $scope.markdown;
});
<html ng-app="myApp">
  <body>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.min.js"></script>
    <div ng-controller="DemoCtrl">
      <h3>Markdown editor</h3>
      <markdown-editor ng-model="markdown" name="markdown"></markdown-editor>
    </div>
  </body>
</html>

这里至少有两个问题:你试图提醒控制器本身,而不是ng-model变量,检查键按下意味着你将永远落后一个击键。

试试这个:

var app = angular.module('myApp', []);
app.directive('markdownEditor', function() {
    return {
        restrict: 'E',
        require: 'ngModel',
        template: '<textarea ng-model="foo"></textarea>',
         link: function(scope, ele, attr, ctrl) {
            ele.on("keyup", function() { // (or use "change" if you don't need to check every single keystroke)
                alert(scope.foo);
            })
        }
    }
});
app.controller('DemoCtrl', function($scope) {
});

https://plnkr.co/edit/wf0NBnQqmgcwE606xeZg

(我强烈建议不要将变量命名为"ngModel"——这非常令人困惑,因为它很难区分变量和 ngModel 指令本身。

您需要添加范围属性的名称,如下所示:

alert(scope.ngModel)

PS:请避免使用ngModel作为变量名

// Code goes here
var app = angular.module('myApp',[]);
app.directive('markdownEditor', function () {
  return {
    restrict: 'E',
    scope: {
      ngModel: "="
    },
    require:'ngModel', 
    template:
    '<textarea ng-model="ngModel"></textarea>' +
    '{{ ngModel}}',
    link:function(scope,ele,attr,ctrl){
      ele.on("keyup",function(){
        alert(scope.ngModel)
      })
    }
  }
});
app.controller('DemoCtrl', function ($scope) {
  var x= $scope.markdown;
});
<html ng-app="myApp">
<body>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.min.js"></script>
  <div ng-controller="DemoCtrl">
    <h3>Markdown editor</h3>
    <markdown-editor ng-model="markdown" name="markdown"></markdown-editor>
  </div>
</body>
</html>