我正在使用AngularJS,我有一个带有ng-repeat
生成的复选框的表单。我想动态生成每个checkbox
的id,我试着这样做:
<label ng-repeat="x in placeTypes">
<input type="checkbox" id='{{x.value}}'>
{{x.display}}
<br>
</label>
但是当我尝试按Id
获取元素时,元素为null
。
答案 0 :(得分:0)
你可以这样做:
<label ng-repeat="x in placeTypes track by $index">
<input type="checkbox" id="checkbox{{$index}}">
{{x.display}}
<br>
</label>
答案 1 :(得分:0)
这应该足够了:
<label ng-repeat="x in placeTypes">
<input type="checkbox" id="{{$index}}">
{{x.display}}
<br>
</label>
您可以在Angular文档中详细了解ngRepeat:https://docs.angularjs.org/api/ng/directive/ngRepeat
答案 2 :(得分:0)
以下是一个工作示例https://plnkr.co/edit/mMzNGsEajOxY7TyiHArL?p=preview
angular.module('app', [])
.component('app', {
template: `<label ng-repeat="x in $ctrl.placeTypes">
<input type="checkbox" id='input-{{x.value}}' component-did-mount>
{{x.display}}
<br>
</label>`,
controller: function($scope) {
this.$onInit = () => {
this.placeTypes = [{
value: '1',
display: 'hello'
}, {
value: '2',
display: 'hello world'
}]
$scope.$on('componentDidMount', () => {
const $el = document.getElementById('input-1');
console.log('$el >>', $el);
})
}
}
}).directive('componentDidMount', ['$timeout', ($timeout) => {
var def = {
restrict: 'A',
transclude: false,
link: (scope, element, attrs) => {
$timeout(() => {
scope.$emit('componentDidMount')
});
}
};
return def;
}]);
angular.element(document).ready(() => {
const bootstrapAngular = () => angular.bootstrap(document.body, ['app'], {});
bootstrapAngular();
});