我被迫创建了一个“国家/地区”。从服务加载数据的指令,显示选择控件中的国家/地区列表,并允许将所选国家/地区绑定到具有ng-model的模型:
这是小提琴:http://jsfiddle.net/4hg4cu9p/1
观点:
<div ng-controller: 'personCtrl'>
<countries ng-model='birthCountry'/>
</div>
代码:
var app = angular.module('myApp', [])
app.controller('personCtrl', ['$scope', function($scope) {
$scope.birthCountry = 'CO';
}]);
app.service('Country', [
'$http', function($http) {
return {
list: function() {
return $http.get('http://restcountries.eu/rest/v1/region/americas', {cache: true});
}
};
}]);
app.directive('countries', [
'Country', '$log', function(Country, $log) {
return {
restrict: 'E',
template: "<select data-ng-model='selectedValue' data-ng-options='country.name for country in countries track by country.alpha2Code'></select?",
require: 'ngModel',
link: function(scope, element, attrs, ngModelCtrl) {
Country.list().then(function(countries) {
scope.countries = countries.data;
});
}
};
}]);
我想使用ngModelController
来:
1.-当模型{{1}}发生变化时,将国家/地区设置为选择控件。
2.-当用户更改选择控件时更改模型birthCountry
。
该模型将birthCountry保存为ISO代码(&#39; CO&#39; =哥伦比亚,&#39;美国&#39; =美国)
这是小提琴:http://jsfiddle.net/4hg4cu9p/1
更新: 感谢@PSL和@apairet,这里是jsfiddle工作: http://jsfiddle.net/4hg4cu9p/3/
答案 0 :(得分:1)
这是一个有效的傻瓜:http://plnkr.co/edit/zw5vfjkkESJ78ypCWggi
ngModel
用作指令的自定义属性 - &gt;使用&#39; my-model&#39;。 更新根据你的评论和@PSL的回答,这是另一个使用ng-model
和指令选项replace: true
http://plnkr.co/edit/YVp6CauBWg3sMLrjwoQL country.alpha2Code
,因此选择了哥伦比亚JS已被修改如下:
var app = angular.module('myApp', []);
app.controller('personCtrl', ['$scope', function($scope) {
$scope.birthCountry = 'CO';
}]);
app.service('Country', [
'$http', function($http) {
return {
list: function() {
return $http.get('http://restcountries.eu/rest/v1/region/americas', {cache: true});
}
};
}]);
app.directive('countries', [
'Country', '$log', function(Country, $log) {
return {
scope: {
myModel: '='
},
restrict: 'E',
template: "<select ng-model='myModel' data-ng-options='country.alpha2Code as country.name for country in countries' track by country.alpha2Code'></select>",
link: function(scope, element, attrs) {
console.log('I am called');
Country.list().then(function(countries) {
console.log(countries);
scope.countries = countries.data;
});
}
};
}]);
和你的标记:
<div ng-controller="personCtrl">
<countries my-model="birthCountry"></countries>
{{birthCountry}}
</div>
答案 1 :(得分:1)
由于您在指令节点指定ng-model
,因此请勿在模板中指定它,而只需在指令中使用replace:true
选项,以便自动应用ng-model。
尝试
{
restrict: 'E',
replace:true,
template: "<select data-ng-options='country.alpha2Code as country.name for country in countries'></select>",
require: 'ngModel',
<强> Demo 强>