在自定义指令中未定义的 NG 模型值打印
ng model value printing undefined inside the custom directive
我创建一个自定义指令,该指令采用一个简单的模板,包括输入类型文本区域,我将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>
相关文章:
- 角度无线电按钮ng模型不起作用
- ng模型内的ng重复的ng重复开始
- 将输入值设置为ng模型属性[Angular]时出现问题
- 自定义指令中的AngularJS ng模型
- 如何为动态创建的文本区域中输入的值更新ng模型
- ng重复中的ng模型-初始化唯一作用域属性
- ng重复变量到ng模型
- 初始化ng模型时,Angular ui选择占位符不起作用
- 角度去抖动(ng模型选项)不起作用
- 即使 ng 模型有值,也使输入字段为空
- 选择框中带有关联的ng模型,选项中带有ng重复
- 为什么我的指令(使用链接)没有出现,并允许ng模型看到它
- AngularJS+IE 11+聚合物=ng模型未更新
- ng模型在$(element).clone()之后不起作用
- 为什么ng选项指令需要ng模型
- 使用引导时间选取器时,没有更新数据ng模型值
- 具有ng重复的动态ng模型
- 有没有一种方法可以在设计模式下将ng模型或工厂绑定到iframe
- 删除ng模型中的ng模型输入值
- Angular.js默认选中不'不适用于ng模型