簡體   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