针对特定标签名称的AngularJS指令

Nao*_*aor 9 javascript angularjs angularjs-directive

如何在AngularJS中强制指令的特定标记?

例如,我想创建一个仅应用于<img>标签的指令.如果用户将此指令放在a上<div>,我不希望该指令处于活动状态.我怎样才能做到这一点?

Eni*_*aRM 6

你有2个选择.

#1使用您现有的指令,添加几行

码:

link: function(scope,element,attr) {

    if (element[0].tagName== 'IMG') {
        //do your stuff
    } else {
        // do nothing or something else
    }
}
Run Code Online (Sandbox Code Playgroud)

#2将你的指令限制为一个元素(如Fizer Khan的回答所示).

.directive('myIMG', function() {
    return {
      restrict: 'E',
      templateUrl: 'img.html',//essentially has <img src=''>
      template: "<img src='scope.path'>",//build out your image tag here which will replace the HTML the directive is on
      transclude: true,
      scope: {
          path: '='
      },
      link: function(scope, element, attr) {

      }
    };
  });
Run Code Online (Sandbox Code Playgroud)

HTML

<myIMG path=''></myIMG>
Run Code Online (Sandbox Code Playgroud)

我个人最喜欢选项2.但我知道这可能更令人生畏,并经常引入其他意想不到的事情.