【问题标题】:Angular: ng-options add custom directiveAngular:ng-options 添加自定义指令
【发布时间】:2016-05-27 10:17:09
【问题描述】:

我想创建一个带有 'selected' 值的选择标签。我正在使用 ng-repeat 执行此操作,因为我无法向 ng-options 添加自定义指令。这是代码。

    <select class="ng-valid ng-dirty" ng-model="selectedCity">
        <option ng-repeat="city in allCities" value="{{city.id}}" after-render-cities>{{city.name}}</option>
    </select>

这增加了一个额外的选项,其值为 =?string:1?我搜索了很多。由于 ng-options 解决了这个问题,但是我必须为每个选项添加指令 after-render-cities。我该如何解决这个问题?

【问题讨论】:

  • “但是,我必须为每个选项添加指令 after-render-cities”。为什么,渲染后城市有什么作用?
  • 它是一个安卓科尔多瓦应用程序。在 html 中呈现数据后,我隐藏了启动画面。
  • 你仍然可以隐藏它,你不需要这个指令。

标签: angularjs angularjs-directive ng-repeat ng-options


【解决方案1】:

使用这个

<select class="ng-valid ng-dirty" ng-model="selectedCity" ng-options="city.id as city.name for city in allCities">
</select>

要选择第一个值,请在控制器中编写以下代码

$scope.selectedCity = $scope.allCities[0].id;

【讨论】:

    【解决方案2】:

    使用 ng-init 求解值 =?string:1?

    <select class="ng-valid ng-dirty" ng-model="selectedCity" ng-init='selectedCity=allCities[0].id'>
        <option ng-repeat="city in allCities" value="{{city.id}}" after-render-cities>{{city.name}}</option>
    </select>
    

    另一个你可以使用 ng-selected fiddle的选择

     <option ng-repeat="(key,city) in allCities" ng-selected='key==0' value="{{city.id}}" after-render-cities>{{city.name}}</option>
     </select>
    

    【讨论】:

    • ng-init 工作。但我不得不删除 ng-model。使用 ng-model 它不起作用。
    • 为什么要删除 ng-model?
    • 不知道。但它不适用于 ng-model。现在我正在尝试在“更改”事件中将值与 ng-model 绑定
    【解决方案3】:

    您可以使用selectng-options 创建自定义directive

    片段

    JS:

    template: "<select ng-options='item.id as item.name for item in list' ng-model='data'></select>",
    

    HTML:

    <div select-option list="list" ng-model='data'></div>
    

    参考演示here

    【讨论】:

      【解决方案4】:

      试试这个代码

      Java 脚本

      var app = angular.module('myApp', []);
      app.controller('SampleController', function ($scope) {
          $scope.Cities = [
               { Id: 1, Name: "New York" },
               { Id: 2, Name: "Colombo" },
               { Id: 3, Name: "Real Madrid" },
               { Id: 4, Name: "Bostan" },
               { Id: 5, Name: "Birmingham" }
            ];
          $scope.City= 3;
      });
      

      HTML

      <select ng-options="C.Id as C.Name for C in Cities" ng-model="City"></select>
      

      Read This Blog, it has everything explained.

      【讨论】:

        猜你喜欢
        • 2019-08-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-02-20
        • 1970-01-01
        • 2018-12-19
        相关资源
        最近更新 更多