在AngularJS指令双向数据绑定 [英] Two way data binding in AngularJS Directives
问题描述
我一直在试图定义指令,这样我就可以在表单中显示不同的小部件,这取决于字段的类型及其参数,存储在数据库中。我需要对不同类型的场景发生反应,因此需要指示来处理布局
I have been trying to define directives so I can display different "widgets" in a form, depending on the type of field and its parameters, which are stored in a database. I need to react to different types of scenarios, hence the need for directives to handle layout.
虽然有几个例子玩,我想出了一个code,它还挺* *作品:
While playing with a few examples, I came up with a code that *kinda* works:
<input type="text" ng-model="myModel" style="width: 90%"/>
<div class="zippy" zippy-title="myModel"></div>
指令
myApp.directive('zippy', function(){
return {
restrict: 'C',
// This HTML will replace the zippy directive.
transclude: true,
scope: { title:'=zippyTitle' },
template: '<input type="text" value="{{title}}"style="width: 90%"/>',
// The linking function will add behavior to the template
link: function(scope, element, attrs) {
// Title element
element.bind('blur keyup change', function() {
scope.$apply(read);
});
var input = element.children();
function read() {
scope.title = input.val();
}
}
}
});
这似乎工作(虽然明显比A *适当* angularJS变量绑定慢),但我想一定有更好的方法来做到这一点。任何人都可以提供一些线索对此事?
This seems to works (albeit noticeably slower than a *proper* angularJS variable binding) but I figure there must be a better way to do this. Can anyone shed some light on the matter?
推荐答案
我不知道你为什么手动触发 $适用
方法,因为你其实并不需要它。
I don't know why you are triggering the $apply
method manually because you actually don't need it.
我编辑您从角页面中使用的例子,包括输入。
它为我工作: http://jsfiddle.net/6HcGS/2/
I edited the example you used from the Angular page and included the input. It works for me: http://jsfiddle.net/6HcGS/2/
HTML
<div ng-app="zippyModule">
<div ng-controller="Ctrl3">
Title: <input ng-model="title">
<hr>
<div class="zippy" zippy-title="title"></div>
</div>
</div>
JS
function Ctrl3($scope) {
$scope.title = 'Lorem Ipsum';
}
angular.module('zippyModule', [])
.directive('zippy', function(){
return {
restrict: 'C',
replace: true,
transclude: true,
scope: { title:'=zippyTitle' },
template: '<input type="text" value="{{title}}"style="width: 90%"/>',
link: function(scope, element, attrs) {
// Your controller
}
}
});
更新
maxisam是正确的,你必须使用 NG-模型
而不是针对像这样的值绑定变量:
UPDATE
maxisam is right, you have to use ng-model
instead of binding the variable against the value like so:
<input type="text" ng-model="title" style="width: 90%"/>
下面是工作的版本: http://jsfiddle.net/6HcGS/3/
这篇关于在AngularJS指令双向数据绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!