见
Why mixing interpolation and expressions is bad practice
.
在这种情况下
ng-options
指令将在插值指令呈现所需表达式之前解析理解表达式。
重新编写组件以输入选项:
app.component('selectField', {
require: {ngModelCtrl: 'ngModel'},
bindings: {
ngModel: '<',
choices: '<'
},
template: `
<select ng-model="$ctrl.ngModel"
ng-change="$ctrl.render($ctrl.ngModel)"
̶n̶g̶-̶o̶p̶t̶i̶o̶n̶s̶=̶"̶{̶{̶:̶:̶$̶c̶t̶r̶l̶.̶i̶n̶p̶u̶t̶O̶p̶t̶i̶o̶n̶s̶E̶x̶p̶r̶e̶s̶s̶i̶o̶n̶}̶}̶"̶ ̶
ng-options="c for c in choices">
</select>
Selected: {{$ctrl.ngModel}}</span>
`,
controller: function() {
this.render = (value) => {
this.ngModelCtrl.$setViewValue(value);
};
}
})
用法:
<select-field ng-model="vm.myColor" choices="vm.colors">
</select-field>
演示
angular.module('myApp', [])
.controller('MainController', function MainController() {
this.colors = ['red', 'blue', 'green'];
this.myColor = this.colors[1]; // blue
})
.component('selectField', {
require: {ngModelCtrl: 'ngModel'},
bindings: {
ngModel: '<',
choices: '<'
},
template: `
<fieldset>Select field
<select ng-model="$ctrl.ngModel"
ng-change="$ctrl.render($ctrl.ngModel)"
ng-options="c for c in $ctrl.choices">
</select>
Selected: {{$ctrl.ngModel}}
</fieldset>
`,
controller: function() {
this.render = (value) => {
this.ngModelCtrl.$setViewValue(value);
};
}
})
<script src="//unpkg.com/angular/angular.js"></script>
<body ng-app="myApp" ng-controller="MainController as vm">
<div>
<select-field ng-model="vm.myColor"
choices="vm.colors">
</select-field>
</div>
<div>
<select ng-model="vm.myColor"
ng-options="color for color in vm.colors">
</select>
Selected: {{vm.myColor}}
</div>
</body>