【发布时间】:2019-09-21 02:09:52
【问题描述】:
我尝试创建一个显示完整国家/地区列表的 Angular 指令,我可以在我的应用程序中重复使用这些指令。
列表显示出来了,我可以根据html中的ng-model预填充列表中的值,但是无法从列表中获取选中的值。当我尝试执行 ctrl.$setViewValue 来更新主范围时出现错误。
这是我目前拥有的代码。
指令
prismanoteApp.directive('countryList', function() {
return {
restrict: 'E',
scope: {
ngModel: '=',
required: '=ngRequired',
label: '@label'
},
templateUrl: '../views/directives/country-list.html',
link : function(scope, element, attrs, ctrl){
console.log("scope", scope, "ctrl",ctrl); //Here is ctrl undefined
scope.countries = [{name: "Netherlands", code: "NL"}] //whole list of countries
if(scope.ngModel){
var index = _.findIndex(scope.countries, {code: scope.ngModel.toUpperCase()})
if(index >= 0){
scope.country = scope.countries[index];
}
}
scope.updateCountry = function(selected){
console.log("SELECTED", selected.code);
ctrl.$setViewValue(selected);
scope.country = selected
}
}
};
});
指令 HTML
<div class="div">
<label for="{{label}}">{{:: "TEXT_COUNTRY" | translate}} id="{{label}}" name="{{label}}"</label>
<ui-select ng-model="country" ng-change="updateCountry($select.selected)" theme="bootstrap">
<ui-select-match placeholder="{{:: 'SELECT_OR_SEARCH_COUNTRY' | translate}}">{{$select.selected.name}}</ui-select-match>
<ui-select-choices repeat="country in countries | filter: $select.search">
<div ng-bind-html="country.name | highlight: $select.search">
</ui-select-choices>
</ui-select>
</div>
HTML
<div class="form-group">
<div class="col-md-12 no-padding-left">
<country-list ng-required="false" label="shopCountry" ng-change="getAddressInfo()" ng-model="currentShop.address.country"></country-list>
</div>
</div>
由于 ctrl 未定义,我无法调用 $setViewValue() 函数,但我怎样才能让它工作呢?
我已经尝试了几个选项,范围变量限制为“A”,在指令中需要。
【问题讨论】:
-
指令定义中需要
require: 'ngModel'。见this帖子
标签: angularjs