如何使用AngularJS指令向选项添加选项?

Fed*_*les 9 javascript angularjs angularjs-directive

我有一个选择标记(用于国家选择),我想使用指令预先填充选项:

<select class="countryselect" required ng-model="cust.country"></select>
Run Code Online (Sandbox Code Playgroud)

我的指示如下

return {
  restrict : "C",
  link: function postLink(scope, iElement, iAttrs) {
     var countries = [
        ["AND","AD - Andorra","AD"],
        ["UAE","AE - Vereinigte Arabische Emirate","AE"]
        ... //loop array and generate opt elements
        iElement.context.appendChild(opt);
    }
  }
Run Code Online (Sandbox Code Playgroud)

我可以使用其他选项填充选择,但ng-model绑定不起作用.即使cust.country具有值(例如"UAE"),也不会选择该选项.

如何使select显示cust.country的值?如果认为我在这里有一些时间问题.

Nor*_*isz 13

你可以使用Angular JS的指令:

标记:

<div ng-controller="MainCtrl">
<select ng-model="country" ng-options="c.name for c in countries"></select>
{{country}}
</div>
Run Code Online (Sandbox Code Playgroud)

脚本:

app.controller('MainCtrl', function($scope) { 
   $scope.countries = [
    {name:'Vereinigte Arabische Emirate', value:'AE'},
    {name:'Andorra', value:'AD'},
  ];

  $scope.country = $scope.countries[1]; 

});
Run Code Online (Sandbox Code Playgroud)

检查选择:Angular Select的文档

编辑与指令

指示:

  app.directive('sel', function () {
    return {
        template: '<select ng-model="selectedValue" ng-options="c.name for c in countries"></select>',
        restrict: 'E',
        scope: {
            selectedValue: '='
        },
        link: function (scope, elem, attrs) {
            scope.countries = [{
                name: 'Vereinigte Arabische Emirate',
                value: 'AE'
            }, {
                name: 'Andorra',
                value: 'AD'
            }, ];
            scope.selectedValue = scope.countries[1];
        }
    };
});
Run Code Online (Sandbox Code Playgroud)

主控制器:

app.controller('MainCtrl', function($scope) {

  $scope.country={};

})
Run Code Online (Sandbox Code Playgroud)

标记:

<div ng-controller="MainCtrl">
<sel selected-value="country"></sel>
{{country}}
</div>
Run Code Online (Sandbox Code Playgroud)

工作实例:示例