Angular:针对一系列视图运行一些JQuery

时间:2016-01-16 01:11:06

标签: javascript jquery angularjs

我已经编写了代码来执行此操作,但我这样做的方式感觉所以不优雅我只是要问是否有人对我有一些基本的建议。基本上我想运行一些JQuery来修改视图子集中的按钮属性(它们全部在同一目录中)。我写了JQuery来做这个,但是我无法弄清楚把这个代码放在哪里

现在,我只是将.js文件推送到这些视图中'目录并在每个视图文件的末尾使用include语句。不完全是MVC ......

情况

界面中出现几个没有可见标签的按钮。有关它们的所有信息都在popover属性中。这是好的(或者可能是它的坏UI或其他什么),只要你不盲目并使用屏幕阅读器,它不会拿起这个popover文本。我想将弹出文本的内容复制到aria-label

手动添加标签"

现在,有问题的按钮是在Angular框架内创建的。按钮的Jade如下所示:

button.customize-option(class='Pet_Egg_{{::egg}}',
   ng-class='{selectableInventory: selectedPotion && !(user.items.pets[egg+"-"+selectedPotion.key]>0) && (Content.dropEggs[egg] || !selectedPotion.premium)}',
   popover-title!=env.t("egg", {eggType: "{{::Content.eggs[egg].text()}}"}),
   popover-trigger='mouseenter', popover-placement='right')

(试图从生产版本中简化它)如果我想在这个按钮上添加aria-label,我可以这样修改:

button.customize-option(class='Pet_Egg_{{::egg}}',
    ng-class='{selectableInventory: selectedPotion && !(user.items.pets[egg+"-"+selectedPotion.key]>0) && (Content.dropEggs[egg] || !selectedPotion.premium)}',
    popover-title!=env.t("egg", {eggType: "{{::Content.eggs[egg].text()}}"}),
    aria-label!=env.t("egg", {eggType: "{{::Content.eggs[egg].text()}}"}),
    popover-trigger='mouseenter', popover-placement='right')

这很有效,buuuuuut还有几十个其他按钮都是用类似但不相同的代码创建的。我正在添加这个咏叹调标签行数十次。那感觉......不优雅。所以我写了一些JQuery!

自动添加标签"

$( document ).ready(function() {
  $("button[popover]").each(function(){
    var text = $(this).attr('popover');
    //not everything has a popover-title. If it does we want that title for the aria-label
    if ($(this).attr('popover-title') !== undefined){
      var title = $(this).attr('popover-title');
      $(this).attr('aria-label', title);
    } else {
      //fall back to just using the popover text if no title is present
      $(this).attr('aria-label', text);
    }
  });
  //turns out some of the popovers are on divs which hold the button
  $("div[popover]").each(function(){
    var label = "";
    if ($(this).attr('popover-title') !== undefined){
      label = $(this).attr('popover-title');
    } else {
      label = $(this).attr('popover');
    }
    $(this).find("button").attr('aria-label', label);
  })
});

我为自己感到骄傲!它从视图中的许多代码更改行转到这个简短易读的JS文件。

JS在哪里???????

我承认自己是一名Angular新手,但基本上我找不到任何可以添加此代码的地方。我收到的关闭是shared/页脚的视图。我可以在那里添加脚本,它将在应用程序的每个路由上运行。这就是某人已经完成分析页脚的方式。但这种方法存在两个问题:

  1. 并非每个网页/路由/视图都需要此aria-label修复。网站上的大多数按钮都有可读标签。我可以添加检查以确保我没有覆盖现有的aria-label,但仍然意味着此脚本不必要地运行

  2. 我不确定每个视图都有popover文本或popover-title可用作aria-label

  3. 那么,那就是我的立场。我不确定自定义控制器(?)或其他什么是解决此问题的最佳方法。

    如果您想查看项目(没有我的更改)this is the folder of 'views',我将转储.js文件并在每个视图中添加include语句。

1 个答案:

答案 0 :(得分:1)

要在AngularJS中执行相同的操作,请创建一个自定义指令以将<style> .entering { background-color:red; } .entering:not(.entering + .leaving) { background-color:green; } </style> <div class="entering">entering</div> <div class="leaving">leaving</div> 属性添加到您的弹出框中。

自动添加标签

aria-label

DEMO on JSFiddle