我正在尝试创建一个指令,该指令将创建一个与创建指令的元素具有相同 ng-model 的输入字段。
到目前为止,这是我想出的:
HTML
<!doctype html>
<html ng-app="plunker" >
<head>
<meta charset="utf-8">
<title>AngularJS Plunker</title>
<link rel="stylesheet" href="style.css">
<script>document.write("<base href=\"" + document.location + "\" />");</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
This scope value <input ng-model="name">
<my-directive ng-model="name"></my-directive>
</body>
</html>
JavaScript
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.name = "Felipe";
});
app.directive('myDirective', function($compile) {
return {
restrict: 'E',
scope: {
ngModel: '='
},
template: '<div class="some"><label for="{{id}}">{{label}}</label>' +
'<input id="{{id}}" ng-model="value"></div>',
replace: true,
require: 'ngModel',
link: function($scope, elem, attr, ctrl) {
$scope.label = attr.ngModel;
$scope.id = attr.ngModel;
console.debug(attr.ngModel);
console.debug($scope.$parent.$eval(attr.ngModel));
var textField = $('input', elem).
attr('ng-model', attr.ngModel).
val($scope.$parent.$eval(attr.ngModel));
$compile(textField)($scope.$parent);
}
};
});
但是,我不确定这是处理这种情况的正确方法,并且存在一个错误,即我的控件未使用 ng-model 目标字段的值进行初始化。
这是上面代码的 Plunker:http://plnkr.co/edit/IvrDbJ
处理这个的正确方法是什么?
编辑:从模板中删除 ng-model="value"
后,这似乎工作正常。但是,我会保持这个问题的开放性,因为我想仔细检查这是这样做的正确方法。
scope
并将其设置为 scope: false
会怎样?在这种情况下如何绑定到 ng-model
?
编辑:这个答案很旧,可能已经过时了。只是一个提醒,所以它不会让人们误入歧途。我不再使用 Angular,所以我无法进行改进。
这实际上是一个很好的逻辑,但你可以稍微简化一下。
指示
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.model = { name: 'World' };
$scope.name = "Felipe";
});
app.directive('myDirective', function($compile) {
return {
restrict: 'AE', //attribute or element
scope: {
myDirectiveVar: '=',
//bindAttr: '='
},
template: '<div class="some">' +
'<input ng-model="myDirectiveVar"></div>',
replace: true,
//require: 'ngModel',
link: function($scope, elem, attr, ctrl) {
console.debug($scope);
//var textField = $('input', elem).attr('ng-model', 'myDirectiveVar');
// $compile(textField)($scope.$parent);
}
};
});
带有指令的 HTML
<body ng-controller="MainCtrl">
This scope value <input ng-model="name">
<my-directive my-directive-var="name"></my-directive>
</body>
CSS
.some {
border: 1px solid #cacaca;
padding: 10px;
}
您可以通过此 Plunker 看到它的实际效果。
这是我看到的:
我理解您为什么要使用“ng-model”,但在您的情况下没有必要。 ng-model 是将现有的 html 元素与范围内的值链接。由于您自己创建了一个指令,因此您正在创建一个“新”html 元素,因此您不需要 ng-model。
编辑正如马克在他的评论中提到的,没有理由不能使用 ng-model,只是为了遵守约定。
通过在指令中显式创建范围(“隔离”范围),指令的范围无法访问父范围上的“名称”变量(我认为这就是您想要使用 ng-model 的原因)。
我从您的指令中删除了 ngModel 并将其替换为您可以更改为任何名称的自定义名称。
使这一切仍然有效的是范围内的“=”符号。查看“范围”标题下的文档文档。
通常,如果您希望指令中的值始终映射到父范围中的值,则您的指令应使用隔离范围(您正确地做到了)并使用 '=' 类型范围。
我综合了所有答案,现在有两种使用 ng-model 属性的方法:
使用复制 ngModel 的新范围
具有在链接上进行编译的相同范围
var app = angular.module('model', []); app.controller('MainCtrl', function($scope) { $scope.name = "Felipe"; $scope.label = "The Label"; }); app.directive('myDirectiveWithScope', function() { return { restrict: 'E', scope: { ngModel: '=', }, // 注意标签没有被复制 template: '
', 替换: true }; }); app.directive('myDirectiveWithChildScope', function($compile) { return { restrict: 'E', scope: true, // 注意标签在范围模板中是如何可见的:'', replace: true, link: function ($scope, element) { // element 将是获取原始指令上的 ng-model 的 div var model = element.attr('ng-model'); $('input',element).attr('ng-model', model); return $compile(element)($scope); } }; }) ; app.directive('myDirectiveWithoutScope', function($compile) { return { restrict: 'E', template: '', replace: true, link: function ($scope, element) { // element 将是获取原始指令上的 ng-model 的 div var model = element.attr('ng-model '); return $compile($('input',element).attr('ng-model', model))($scope); } }; }); app.directive('myReplacedDirectiveIsolate', function($compile) { return { restrict: 'E', scope: {}, template: '', replace: true }; }); app.directive('myReplacedDirectiveChild', function($compile) { return { restrict: 'E', scope: true, template: '', replace: true }; }); app.directive('myReplacedDirective', function($compile) { return { restrict: 'E', template: '', replace: true }; }); .some { 边框:1px 实心 #cacaca;填充:10px; }尝试输入chi ld 范围的,它们将值复制到子范围中,这会破坏与父范围的链接。
还要注意删除 jQuery 是如何做到的,所以只有 new-isolate-scope 版本有效。
最后请注意,replace+isolate 作用域仅适用于 AngularJS >=1.2.0
我不确定我是否喜欢链接时的编译。但是,如果您只是用另一个元素替换元素,则不需要这样做。
总而言之,我更喜欢第一个。只需将范围设置为 {ngModel:"="}
并将 ng-model="ngModel"
设置为模板中所需的位置。
更新:我内联了代码片段并为 Angular v1.2 更新了它。事实证明,隔离范围仍然是最好的,尤其是在不使用 jQuery 时。所以归结为:
您是否替换单个元素:只需替换它,不理会范围,但请注意替换在 v2.0 中已弃用: app.directive('myReplacedDirective', function($compile) { return { restrict: 'E', template : '', 替换: true }; });
否则使用这个: app.directive('myDirectiveWithScope', function() { return { restrict: 'E', scope: { ngModel: '=', }, template: '
' }; });ng-model
会有任何问题或额外开销吗?
没那么复杂:在您的指令中,使用别名:scope:{alias:'=ngModel'}
.directive('dateselect', function () {
return {
restrict: 'E',
transclude: true,
scope:{
bindModel:'=ngModel'
},
template:'<input ng-model="bindModel"/>'
}
在您的 html 中,正常使用
<dateselect ng-model="birthday"></dateselect>
只有在需要访问模型的 $viewValue 或 $modelValue 时才需要 ng-model。请参阅NgModelController。在这种情况下,您将使用 require: '^ngModel'
。
其余的请参见Roys answer。
^
才应该存在
这是一个有点晚的答案,但我发现这个关于 NgModelController
的很棒的 post,我认为这正是您正在寻找的。
TL;DR - 您可以使用 require: 'ngModel'
,然后将 NgModelController
添加到您的链接函数中:
link: function(scope, iElement, iAttrs, ngModelCtrl) {
//TODO
}
这样,无需 hack - 您使用的是 Angular 的内置 ng-model
我不会通过属性设置 ngmodel,您可以在模板中直接指定它:
template: '<div class="some"><label>{{label}}</label><input data-ng-model="ngModel"></div>',
plunker:http://plnkr.co/edit/9vtmnw?p=preview
从 Angular 1.5 开始,可以使用组件。组件很容易解决这个问题。
<myComponent data-ng-model="$ctrl.result"></myComponent>
app.component("myComponent", {
templateUrl: "yourTemplate.html",
controller: YourController,
bindings: {
ngModel: "="
}
});
在 YourController 中,您需要做的就是:
this.ngModel = "x"; //$scope.$apply("$ctrl.ngModel"); if needed
input ng-model="$ctrl.ngModel"
并且它也将与 $ctrl.result 同步。
创建隔离范围是不可取的。我会避免使用范围属性并做这样的事情。 scope:true 为您提供了一个新的子范围,但不隔离。然后使用 parse 将本地范围变量指向用户提供给 ngModel 属性的同一对象。
app.directive('myDir', ['$parse', function ($parse) {
return {
restrict: 'EA',
scope: true,
link: function (scope, elem, attrs) {
if(!attrs.ngModel) {return;}
var model = $parse(attrs.ngModel);
scope.model = model(scope);
}
};
}]);
contenteditable
指令示例——forms page、NgModelController page——都使用 ng-model。 ngModelController 页面说这个控制器“旨在通过其他指令进行扩展”。hg-model
传入的其他地方的一致性(而不是耦合问题,IMO)。这样,无论是<input>
还是自定义指令,数据上下文始终使用 ng-model,从而简化了 HTML 编写器的认知开销。即,它使 HTML 编写者不必找出每个指令的my-directive-var
的名称是什么,特别是因为没有自动完成功能可以帮助您。ng-model-options
或任何其他 ng 模型的东西,是吗?