Angularjs Ng从链接中的模板中转移数据
我已编写了以下指令:Angularjs Ng从链接中的模板中转移数据,angularjs,angularjs-directive,Angularjs,Angularjs Directive,我已编写了以下指令: angular.module('solarquote.directives', []).directive('editfield', function() { return { restrict: 'A', transclude: true, template: '<span ng-hide="editorEnabled" ng-transclude></span>' + // viewable field '<
angular.module('solarquote.directives', []).directive('editfield', function() {
return {
restrict: 'A',
transclude: true,
template: '<span ng-hide="editorEnabled" ng-transclude></span>' + // viewable field
'<span ng-show="editorEnabled"><input class="input-medium" ng-model="editableField"></span>', // editable field
link: function(scope, elm, attrs, ctrl) {
scope.editorEnabled = false;
scope.editableField = elm.children[0].children[0].innerText;
}
};
})
角度.module('solarquote.directives',[]).directive('editfield',function(){
返回{
限制:“A”,
是的,
模板:“”+//可查看字段
'',//可编辑字段
链接:函数(范围、elm、属性、ctrl){
scope.editorEnabled=false;
scope.editableField=elm.children[0]。children[0]。innerText;
}
};
})
在html中,在ng重复中:
<span editfield>{{ item.fields.name }}</span>
{{item.fields.name}
我想用ng transclude中相同的内容预填充指令模板中的输入字段。遍历DOM并获取文本将生成:{{item.fields.name}},而不是呈现的数据:“Bob”(或任何名称)
访问转置数据的最佳方式是什么
多亏了无法将您在转换块中指定的表达式指定给
ng model
。这是因为转换块可以是像{{functionValue()}}
或{{field1+':'+field2}}}
这样的表达式。Angular根本不知道如何反转这些表达式
您可以做的是提供要更新的模型的引用。请参阅以下punkler(需要jQuery)
指令('editfield',函数(){
变量模板=“”+
''+
'';
返回{
限制:“A”,
模板:模板,
范围:{
编辑字段:'='
},
是的,
链接:函数(范围、元素、属性){
var input=element.find('input');
input.on('blur',function(){
scope.editorEnabled=false;
作用域:$apply();
});
元素绑定('单击',函数(){
scope.editorEnabled=!scope.editorEnabled;
作用域:$apply();
input.focus();
})
}
};
})
您不能简单地将转置的值(
{{model}}
)放入ng model
中,因为您可以在那里编写任何表达式{}
。您必须使用类似
directive('editfield', function() {
var template = ''+
'<span ng-show="editorEnabled"><input class="input-medium" ng-model="editfield"></span>'+
'<span ng-hide="editorEnabled" ng-transclude></span>';
return {
restrict: 'A',
template: template,
scope:{
editfield:'='
},
transclude:true,
link: function(scope, element, attrs) {
var input = element.find('input');
input.on('blur',function(){
scope.editorEnabled=false;
scope.$apply();
});
element.bind('click',function(){
scope.editorEnabled=!scope.editorEnabled;
scope.$apply();
input.focus();
})
}
};
})