var testModule = angular.module("testModule",[]);
testModule.directive('addVehicle',function() {
return {
restrict: 'A',
scope: false,
link: function(scope, instanceElement, attributes) {
instanceElement.on('click',function() {
angular.element(document.getElementById('vehicles')).append('<vehicle-table></vehicle-table>');
});
}
}
});
testModule.directive('vehicleTable',function() {
return {
restrict: 'E',
template: '<table class="vehicleTable">' +
'<tr><td class="vehicleData"><select></select></td></tr>' +
'<tr><td class="vehicleData"><input type="text"></td></tr> ' +
'<tr><td class="vehicleDataEnd"><input type="text"></td></tr>' +
'</table>'
}
});
上面是我的角度JS片段。当我点击addVehicle(这是按钮元素的属性)时,我只将vehicleTable作为标签,而不是将其模板插入DOM中。这可能有什么问题?
答案 0 :(得分:0)
因为指令需要在使用其模板和行为进行渲染之前正确编译和处理,所以只附加一个元素。
使用编译服务 $ compile
var el = $compile( '<vehicle-table></vehicle-table>' )( scope );
angular.element(document.getElementById('vehicles').append( el );
指令的完整代码将是
testModule.directive('addVehicle',function() {
return {
restrict: 'A',
scope: false,
link: function(scope, instanceElement, attributes) {
instanceElement.on('click',function() {
var el = $compile( '<vehicle-table></vehicle-table>' )( scope );
angular.element(document.getElementById('vehicles').append( el );
});
}
}
});
答案 1 :(得分:0)
在您的示例中,您需要$编译添加的指令:
link: function(scope, instanceElement, attributes) {
instanceElement.on('click', function() {
var newElem = $compile(angular.element("<vehicle-table>"))(scope)
instanceElement.append(newElem);
});
}
但仅仅因为你正在写一个指令,并不意味着你应该放弃正常的角度模式。你可以这么做:
testModule.directive('addVehicle', function() {
return {
restrict: 'A',
scope: false,
template: "<vehicleTable ng-repeat='v in vehicles'></vehicleTable>",
link: function(scope, instanceElement, attributes) {
scope.vehicles = [];
instanceElement.on('click', function() {
scope.vehicles.push({}); // or whatever the object you need
});
}
}
});