Angular.js - 使用 ng-options 将类添加到选项

2024-04-14

有人问过类似的问题(如何在带有 ng-options 的 select 中使用 ng-class https://stackoverflow.com/questions/15264051/how-to-use-ng-class-in-select-with-ng-options),但我也添加了我的,因为它与其他人的问题的答案有关。

解决方案很棒,但我不太明白。

答案是创建一个指令 -http://plnkr.co/edit/rbc4GWBffi4eFYhbvS6u?p=preview http://plnkr.co/edit/rbc4GWBffi4eFYhbvS6u?p=preview.

我想做同样的事情,但添加的类应该与 items.name 相同。我怎么做?

console.clear();

var app = angular.module('angularjs-starter', []);

app.controller('MainCtrl', function($scope) {
  $scope.items = [
    { name: 'foo', id: 1, eligible: true },
    { name: 'bar', id: 2, eligible: false },
    { name: 'test', id: 3, eligible: true }
    ];
});

app.directive('optionsClass', function ($parse) {
  return {
    require: 'select',
    link: function(scope, elem, attrs, ngSelect) {
      // get the source for the items array that populates the select.
      var optionsSourceStr = attrs.ngOptions.split(' ').pop(),
      // use $parse to get a function from the options-class attribute
      // that you can use to evaluate later.
          getOptionsClass = $parse(attrs.optionsClass);
          
      scope.$watch(optionsSourceStr, function(items) {
        // when the options source changes loop through its items.
        angular.forEach(items, function(item, index) {
          // evaluate against the item to get a mapping object for
          // for your classes.
          var classes = getOptionsClass(item),
          // also get the option you're going to need. This can be found
          // by looking for the option with the appropriate index in the
          // value attribute.
              option = elem.find('option[value=' + index + ']');
              
          // now loop through the key/value pairs in the mapping object
          // and apply the classes that evaluated to be truthy.
          angular.forEach(classes, function(add, className) {
            if(add) {
              angular.element(option).addClass(className);
            }
          });
        });
      });
    }
  };
});
/* CSS goes here */
.is-eligible {
  color: green;
}
.not-eligible {
  color: red;
}
<!DOCTYPE html>
<html ng-app="angularjs-starter">
  
  <head lang="en">
    <meta charset="utf-8">
    <title>Custom Plunker</title>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.2/angular.min.js"></script>
    <link rel="stylesheet" href="style.css">
    <script>
      document.write('<base href="' + document.location + '" />');
    </script>
    <script src="app.js"></script>
  </head>
  
  <body ng-controller="MainCtrl">
    <select ng-model="foo" ng-options="x.name for x in items" 
            options-class="{ 'is-eligible' : eligible, 'not-eligible': !eligible }"></select>
  </body>

</html>

提前致谢


将此逻辑硬编码到指令中的一种方法是使用option.text():

      angular.element(option).addClass(option.text()); // 

但是,这会忽略该表达式。http://plnkr.co/edit/46HndjYtg6HUbblnceNr?p=preview http://plnkr.co/edit/46HndjYtg6HUbblnceNr?p=preview

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Angular.js - 使用 ng-options 将类添加到选项 的相关文章

  • 如何重置表单中的 $dirty

    我在使用时遇到一个问题 dirty在我的申请表中 问题是一旦您更改表单字段 值 dirty将被设置为true但现在当您撤消更改时 它不会重置 dirty价值false 我们可以重置 dirty价值false手动但之后当您再次更改表单字段值时
  • Angularjs $http 等待响应

    我是 javascript angularjs 的新手 我想在某些元素上完成鼠标悬停时显示引导弹出窗口 我为此创建了一个指令 function angular app app directive popOver window http fu
  • 按 Chartjs 条形图的键对对象进行分组

    我正在尝试使用 Chart js 创建条形图 我在尝试根据每个用户的状态创建分组条形图时陷入困境 这是数据 statusId 0 firstName Joe status appealed count 1 statusId 0 firstN
  • XmlHttpRequest CORS POST 发送时不带 cookie

    我有一个 Rails 服务为我的 AngularJS 前端应用程序返回数据 该服务配置为通过返回足够的标头来允许 CORS 请求 当我发出 GET 请求来接收数据时 会发送 CORS 标头 以及我之前在登录时收到的会话 cookie 您可以
  • 将安全的 Grafana 嵌入到 Web 应用程序中

    我想使用 AngularJS 将 Grafana 嵌入到我的 Web 应用程序中 目标是 当用户使用我的应用程序时 她应该能够单击按钮并加载 Grafana UI 就其本身而言 这是一项简单的任务 为此 我使用 apache 代理 Graf
  • AngularJs 从自身调用内部服务函数

    我构建了一个发出多个请求的简单服务 该服务有两种方法 我无法从服务内的另一种方法调用一种方法 Plunkr http plnkr co edit 2fERik4uTxbxlVOhncMd p preview http plnkr co ed
  • Angularjs 抛出 TypeError:无法读取未定义的属性“indexOf”

    我正在尝试调试上面的代码 我觉得这非常有用 gt 我什至找不到代码中的问题 也不知道从哪里开始 因为 Angularjs 对我来说仍然很新 我正在尝试本地化 Angularjs 应用程序 我知道为了获得帮助而缺少很多上下文 但我正在尝试查看
  • 在 Angular ui-router 中更改状态而不更改浏览器历史记录

    假设我们有这样的逻辑 从状态A改变到状态B 每当我们到达状态 B 时 应用程序总是通过调用将我们重定向到状态 C state go stateC 现在我们处于状态C 我的问题是如何从状态 C 返回状态 A 考虑到状态 A 可以是我们在运行时
  • AngularJS,使用没有后退按钮刷新的路由

    我在用着angularJS使用 AJAX 构建一个简单的单页应用程序 但是当用户使用本机后退按钮时我遇到了问题 angular module myApp ionic myApp controllers myApp services conf
  • 如何在 Angular 中使用 ng-options 过滤选择?

    我编写了以下 Angular 应用程序的概念验证 该应用程序允许人们投票选举美国总统
  • 如何使用 $http.get 获取 304 状态代码?

    如何使用 http get 获取 304 状态代码 http get menu json success function data status headers scope menu data console log status sho
  • 函数调用后的两组括号

    我正在寻找如何filters http docs angularjs org api ng 24filter在 Angularjs 中工作 我发现我们需要发送 2 组括号 filter number number fractionSize
  • 当我的网页上有一个持续时间计数器时,AngularJS 有什么帮助吗?

    我有一个使用 Angular ui router 的应用程序 当路由器设置为某种状态时 我希望将计时器设置为例如 2 小时 当它设置为另一个状态时 我想让计数器倒计时 我希望在屏幕上显示剩余时间 有谁有关于如何实现此功能的代码示例吗 如果有
  • 选择器的内部文本

    我尝试从此标记中获取内部文本 span class ng binding ng scope Displaying results 1 25 of 17 430 span 使用此选择器 document querySelectorAll di
  • AngularJS 插值错误

    我正在显示房间的属性 作为我正在开发的房间管理应用程序的一部分 这是输出 如您所见 Beamer 英文投影仪 的值为 Sony lamp 01 12 2013 此输出是正确的 但当我打开控制台时 我看到一些有关插值的错误 更大的分辨率 Ca
  • 在 Angular e2e 测试中获取浏览器路径会导致异常

    我有一个简单的 e2e 测试来验证路由重定向是否有效 跑步者 html 场景 js use strict describe e2e function beforeE
  • 用户脚本 - 有没有办法将 jquery 代码注入 angularjs dom?

    所以我正在尝试为一个网站创建用户脚本 我无法更改网站的任何源代码 因为它不是我的 网站到处都使用 AngularJS 控制器 我研究了几天如何做到这一点 但没有成功 所以我尝试注入代码 nav after div test div 当我通过
  • Protractor+AngularJS+Jasmine - 测试按住项目

    AngularJS 和 Protractor 非常新 但我认为到目前为止我正在朝着正确的方向前进 我的网站有一个项目列表 当您单击该项目并按住 X 秒时 它会打开一个模式窗口 我如何在 Protractor Jasmine 中模拟这种行为
  • Angular - 如何从 DOM 中删除我使用过 $compile 的元素?

    我需要的是两个 ng views 的功能 因为我不能 我想更改某些内容的innerHTML 并编译它 我遇到的问题是 当我再次更改内容时 我可以编译 但是 Angular 是否会自行删除绑定 或者我必须手动执行此操作 如果是这样 怎么办 编
  • AngularJS:Array.prototype.find() 在 Chrome 中不起作用

    我遇到一个问题 我的角度代码可以在 Firefox 中工作 但不能在 Chrome 中工作 浏览器控制台打印如下 TypeError undefined is not a function at setSelectedColor http

随机推荐