我是 Angular 的新手,但仍然痛苦地纠结于自定义指令。
我想重用这段 HTML
<ui-select ng-model="model.selectedLanguages" multiple search-enabled="true" theme="select2" style="width: 300px;">
<ui-select-match placeholder="Pick one...">{{$item.name}}</ui-select-match>
<ui-select-choices repeat="lang.id as lang in langs |filter: { name : $select.search }">
<div ng-bind-html="lang.name | highlight: $select.search" ></div>
</ui-select-choices>
</ui-select>
通过将其包装到我的自定义指令中:
<language-picker ng-model="model.selectedLanguages"/>
像这样的东西:
app.directive('languagePicker', function() {
return {
template : '<ui-select ng-model="**PARENT'S NGMODEL**" multiple search-enabled="true" theme="select2" style="width: 300px;"><ui-select-match >{{$item.name}}</ui-select-match><ui-select-choices repeat="lang.id as lang in langs | filter: { name : $select.search }"><div ng-bind-html="lang.name | highlight: $select.search"></div></ui-select-choices></ui-select>',
restrict : 'E',
require : 'ngModel',
replace : true
....
};
});
但是我如何从我的language-picker
to the ui-select
指令?
UPDATE
使用下面的建议,我让它与 ui-select 一起工作,但外部模型根本没有更新,请参阅plnkr.co/edit/Y43dmMGIc5GxM9fLoNPW http://plnkr.co/edit/Y43dmMGIc5GxM9fLoNPW,可能是因为它的子作用域和父作用域保持不变?
UPDATE 2
我让它以一种复杂的方式工作,这对我来说看起来很可怕,因为我不知道为什么它首先“工作”(看看控制器中发生的奇怪的事情):
app.directive('languagePicker', function(LanguageService) {
return {
templateUrl : 'LanguagePickerTpl.html',
restrict : 'E',
scope : {
languages : '='
},
controller : function($scope, LanguageService) {
console.log($scope);
$scope.langs = LanguageService.get();
$scope.model = $scope;
}
};
})
模板:
<ui-select ng-model="model.languages" multiple search-enabled="true"
theme="select2" style="width: 300px;">
<ui-select-match>{{$item.name}}</ui-select-match>
<ui-select-choices repeat="lang.id as lang in langs | filter: { name : $select.search }">
<div ng-bind-html="lang.name | highlight: $select.search"></div>
</ui-select-choices>
</ui-select>
如果有人能解释发生了什么,我会非常高兴(“工作”示例在这里http://plnkr.co/edit/B53F9sc7UGkj0uxUpC17 http://plnkr.co/edit/B53F9sc7UGkj0uxUpC17
)