【发布时间】:2016-03-30 15:29:01
【问题描述】:
我的指令递归构建选择输入有问题。
我有一些模块有一些功能,这些功能可以有一些像这样的子功能:
[
0: {
module_name : administration
fonctions : [
{
fonction_id : 1
fonction_name : getAdministration
children : [
{
fonction_id : 2
fonction_name : getParameters
children : []
},
{
fonction_id : 3
fonction_name : getModules
children : []
},
...
]
},
]
},
1: {
module_name : Account
fonctions : [
{
fonction_id : 4
fonction_name : CreateAccount
children : []
},
{
fonction_id : 5
fonction_name : EditAccount
children : []
},
....
]
},
...
]
目标是为每个模块在select中构建optgroup,并在option中放入该模块的每个功能,如果功能有孩子,继续同一个 optgroup 否则创建一个新的 optgroup 来获得这个结果:
<select>
<optgroup label='Administration'>
<option value='1'>getAdministration</option>
<option value='2'>getParameters</option>
<option value='3'>getModules</option>
...
</optgroup>
<optgroup label='Account'>
<option value='1'>CreateAccount</option>
<option value='2'>EditAccount</option>
...
</optgroup>
</select>
为了制定这些指令,我受到这篇文章的启发:http://sporto.github.io/blog/2013/06/24/nested-recursive-directives-in-angular/
看我的两条指令:
WcSelectOptionGroup:
angular.module('app.administration').directive('wcSelectOptionGroup', function()
{
return {
restrict: 'E',
replace: true,
scope: {
elts: '=',
selectId: '='
},
template: '<select><optgroup' +
'label="{{ elt.module_name }}"' +
'ng-repeat="elt in elts">' +
'<wc-select-option' +
'ng-repeat="fnct in elt.fonctions"' +
'ng-selected="fnct.fonction_id === selectId"' +
'item="fnct"' +
'selectId="selectId">' +
'</wc-select-option>' +
'</optgroup></select>',
link: function(scope)
{
console.log('hello 1!!!!!!!');
}
};
});
第二个:
WcSelectOption:
angular.module('app.administration').directive('wcSelectOption', function($compile)
{
return {
restrict: 'E',
replace: true,
scope: {
item: '=',
selectId: '='
},
template: '<option' +
'value="{{ item.fonction_id }}"' +
'ng-selected="item.fonction_id === selectId">' +
'{{ item.fonction_title }}' +
'</option>',
link: function(scope, element, attrs)
{
console.log('hello 2!!!!!!!');
angular.forEach(scope.item.children, function(child)
{
$compile('<wc-select-option' +
'item="child"' +
'selectId="selectId">' +
'</wc-select-option>')
(scope, function(cloned, scope)
{
element.append(cloned);
});
});
}
};
});
和 html :
<select
class="form-control"
name="parent"
ng-model="fonction.fonction_parent_id"
required>
<option
value="0"
ng-selected="fonction.fonction_parent_id === null">
Aucun
</option>
<optgroup label="{{ $root.getWord('Functions not assigned') }}">
<option
ng-repeat="fnct in fonctions.not_assigned"
value="{{ fnct.fonction_id }}"
ng-selected="fnct.fonction_id===fonction.fonction_parent_id">
{{ fnct.fonction_name }}
</option>
</optgroup>
<wc-select-option-group
elts="modules"
selectId="fonction.fonction_parent_id">
</wc-select-option-group>
</select>
当我运行应用程序时,指令 WcSelectOptionGroup 不会执行,因为当我放置一个 console.log('hello 1!!!') 时,什么都没有发生...... 我不明白为什么。
所以如果你有一些想法:) 提前致谢
【问题讨论】:
标签: javascript angularjs recursion angularjs-directive