我一直在尝试定义指令,因此我可以在表单中显示不同的"小部件",具体取决于存储在数据库中的字段类型及其参数.我需要对不同类型的场景做出反应,因此需要指令来处理布局.
在玩几个例子时,我想出了一个*有点*的代码:
<input type="text" ng-model="myModel" style="width: 90%"/>
<div class="zippy" zippy-title="myModel"></div>
Run Code Online (Sandbox Code Playgroud)
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();
}
}
}
});
Run Code Online (Sandbox Code Playgroud)
这似乎有效(虽然明显慢于*适当的*angularJS变量绑定)但我认为必须有更好的方法来做到这一点.谁能解释一下这个问题呢?