简体   繁体   English

指令可以在HTML标签之外使用吗?

[英]Can directives be used outside of HTML tags?

Since learning Angular a few months ago, I was under the impression that ` directives are special functions which are activated by placing a keyword in an HTML tag in one of two ways - either as an element, as an attribute. 自从几个月前学习Angular以来,给我的印象是` 指令是特殊的功能,可以通过以下两种方式之一将关键字放在HTML标签中来激活这些指令 -既可以作为元素,也可以作为属性。

For example: 例如:

<my-directive>Something</my-directive>

or 要么

<div my-directive></div>

However, in a Git project I came across , I'm seeing a directive used in a totally different way and I don't understand how it works. 但是, 在一个Git项目中 ,我遇到了一个指令,它以完全不同的方式使用,我不知道它是如何工作的。

The directive is supposedly activated just by adding a key-value of css: {} to a .state() function in ui-router. 假设仅通过将css: {}的键值添加到ui-router中的.state()函数来激活该指令。

For instance: 例如:

.state('state1', {
      url: '/state',
      controller: 'StateCtrl',
      templateUrl: 'views/my-template.html',
      data: {
        css: 'styles/style1.css'
      }
    })

How does this "directive" works? 这个“指令”如何工作?

---------- ----------

The Javascript source of the directive copied from the Git project, so it's preserved in this question: 从Git项目复制的指令的Javascript源,因此保留在以下问题中:

/**
 * @author Manuel Mazzuola
 * https://github.com/manuelmazzuola/angular-ui-router-styles
 * Inspired by https://github.com/tennisgent/angular-route-styles
 */

'use strict';

angular
  .module('uiRouterStyles', ['ui.router'])
  .directive('head', ['$rootScope', '$compile', '$state', '$interpolate',
    function($rootScope, $compile, $state, $interpolate) {
      return {
        restrict: 'E',
        link: function(scope, elem){
          var start = $interpolate.startSymbol(),
              end = $interpolate.endSymbol();
          var html = '<link rel="stylesheet" ng-repeat="(k, css) in routeStyles track by k" ng-href="' + start + 'css' + end + '" >';
          elem.append($compile(html)(scope));

          // Get the parent state
          var $$parentState = function(state) {
            // Check if state has explicit parent OR we try guess parent from its name
            var name = state.parent || (/^(.+)\.[^.]+$/.exec(state.name) || [])[1];
            // If we were able to figure out parent name then get this state
            return name && $state.get(name);
          };

          scope.routeStyles = [];
          $rootScope.$on('$stateChangeStart', function (evt, toState) {
            // From current state to the root
            scope.routeStyles = [];
            for(var state = toState; state && state.name !== ''; state=$$parentState(state)) {
              if(state && state.data && state.data.css) {
                if(!Array.isArray(state.data.css)) {
                  state.data.css = [state.data.css];
                }
                angular.forEach(state.data.css, function(css) {
                  if(scope.routeStyles.indexOf(css) === -1) {
                    scope.routeStyles.push(css);
                  }
                });
              }
            }
            scope.routeStyles.reverse();
          });
        }
      };
    }
  ]);

The directive is named after HTML <head> tag. 该指令以HTML <head>标记命名。 It presumes that your html page contains a <head> tag and treats that as your directive declaration. 假定您的html页面包含<head>标记,并将其视为您的指令声明。 It also presumes that the angular ng-app declaration is placed on <html> tag. 它还假定将ng-app角度声明放在<html>标记上。

The directive does nothing but erases and writes css <link> tags within the html head tag content everytime the state changes. 该指令不执行任何操作,但每次状态更改时,都会擦除并在html头标记内容中写入css <link>标记。

Note that it is not preferable to name your directives after native html tags. 请注意,以本机html标签命名指令不是可取的。 This is why you see angular directives prepended by 'ng' so as to clearly demarcate them as angular tags. 这就是为什么您会看到以“ ng”开头的角度指令,以便清楚地将它们划分为角度标签的原因。 Otherwise, it can lead to confusion, as you have yourself found out with trying to understand this piece of git code. 否则,可能会导致混乱,因为您发现自己试图理解这段git代码。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 AngularJS指令中自定义HTML标记的后果 - Consequences of Custom HTML Tags in AngularJS Directives 在任何地方使用自定义指令而不是常规HTML标记是一个性能损失? - Having Custom Directives instead of regular HTML tags everywhere is a performance hit? 使用Angular指令用HTML标签替换Bootstrap类分配 - Using Angular Directives to Replace Bootstrap Class Assignment with HTML Tags 使用角度指令时将html标签视为纯文本 - html tags considered as plain text when using angular directives AngularJS指令:将HTML属性作为字符串,用作字典键 - AngularJS Directives: Take a HTML attribute as a string, used as a dictionary key 标签的角度指令 - Angular Directives For Tags 父模块指令可以在控制器等子模块中使用吗? - Can parent module directives be used in child modules like controllers? 混合应用程序可以在 AngularJS 和 Angular 中使用组件或指令吗? - Can components or directives be used in both AngularJS and Angular for a hybrid app? 可以使用wiredep或其他任何方式插入<script> tags in HTML to include all .js files in given directories? - Can wiredep or anything else be used to insert <script> tags in HTML to include all .js files in given directories? AngularJS 指令作为“自定义”HTML 标签:这不是危险的并且可能与未来的 HTML 版本冲突吗? - AngularJS directives as "custom" HTML tags: isn't this dangerous and may conflict with future HTML versions?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM