繁体   English   中英

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

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

自从几个月前学习Angular以来,给我的印象是` 指令是特殊的功能,可以通过以下两种方式之一将关键字放在HTML标签中来激活这些指令 -既可以作为元素,也可以作为属性。

例如:

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

要么

<div my-directive></div>

但是, 在一个Git项目中 ,我遇到了一个指令,它以完全不同的方式使用,我不知道它是如何工作的。

假设仅通过将css: {}的键值添加到ui-router中的.state()函数来激活该指令。

例如:

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

这个“指令”如何工作?

----------

从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();
          });
        }
      };
    }
  ]);

该指令以HTML <head>标记命名。 假定您的html页面包含<head>标记,并将其视为您的指令声明。 它还假定将ng-app角度声明放在<html>标记上。

该指令不执行任何操作,但每次状态更改时,都会擦除并在html头标记内容中写入css <link>标记。

请注意,以本机html标签命名指令不是可取的。 这就是为什么您会看到以“ ng”开头的角度指令,以便清楚地将它们划分为角度标签的原因。 否则,可能会导致混乱,因为您发现自己试图理解这段git代码。

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM