【发布时间】:2017-07-29 17:32:34
【问题描述】:
在 ng-repeat 中编译指令时,谁能帮我解决作用域问题?
https://plnkr.co/edit/y6gfpe01x3ya8zZ5QQpt?p=preview
自定义指令input-by-type 可以根据变量类型将<div> 替换为适当的<input> - 这在ng-repeat 中使用之前可以正常工作。
正如您在 plnkr 示例中所见,该指令按预期工作,直到在 ng-repeat 中使用。
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.data = {};
$scope.inputs = [
{ name: 'Some Text', type: 'text', id: 1 },
{ name: 'EMail', type: 'email', id: 2 },
{ name: 'Age', type: 'number', id: 3 }
];
});
app.directive('inputByType', ['$compile', '$interpolate', function($compile, $interpolate){
return {
restrict: 'A', // [attribute]
require: '^ngModel',
scope: true,
compile: function(element, attrs, transclude){
var inputs = {
text: '<input type="text" name="'+attrs.name+'" ng-model="'+attrs.ngModel+'" ng-disabled="'+attrs.ngDisabled+'" ng-required="'+attrs.ngRequired+'" placeholder="...">',
email: '<input type="email" name="'+attrs.name+'" ng-model="'+attrs.ngModel+'" ng-disabled="'+attrs.ngDisabled+'" ng-required="'+attrs.ngRequired+'" placeholder="...@...">',
number: '<input type="number" name="'+attrs.name+'" ng-model="'+attrs.ngModel+'" ng-disabled="'+attrs.ngDisabled+'" ng-required="'+attrs.ngRequired+'" placeholder="###">',
};
return function(scope){
var type = $interpolate(attrs.inputByType)(scope); // Convert input-by-type="{{ some.type }}" into a useable value
var html = inputs[type] || inputs.text;
var e = $compile(html)(scope);
element.replaceWith(e);
console.log(type, html, element, e);
};
},
};
}]);
如果我手动引用inputs[0] 来编译input-by-type 指令,它就可以正常工作:
<label>
{{ inputs[0].name }}
<div input-by-type="{{ inputs[0].type }}" name="myInputA" ng-model="data.A" ng-required="true"></div>
</label>
但是,当我将其包装在 ng-repeat 块中时,编译失败并出现一些意外输出:
<label ng-repeat="input in inputs">
{{ input.name }}
<div input-by-type="{{ input.type }}" name="myInput{{ $index }}" ng-model="data[input.id]" ng-required="true"></div>
</label>
预期输出:
实际输出:
【问题讨论】:
标签: angularjs angularjs-directive angularjs-compile