AngularJS指令ng如果在头部和身体元素处

AngularJS directive ng-if at head and body elements

本文关键字:体元 元素 头部 指令 ng 如果 AngularJS      更新时间:2023-09-26

在html头部和主体元素处设置AngularJS ng-if指令是否有效?

<!DOCTYPE html>
<html ng-app="myApp">
  <head ng-if="condition">
    <!-- if conditon is true -->
  </head>
  <head ng-if="condition">
    <!-- if condition is false -->
  </head>
  <body ng-controller="MyCtrl" ng-if="condition">
    <!-- if conditon is true -->
  </body>
  <body ng-controller="MyCtrl" ng-if="condition">
    <!-- if conditon is false-->
  </body>
</html>

它行得通吗?

这里有一个动态加载CSS文件的示例指令,尽管卸载CSS文件是另一个问题,因为你需要跟踪添加了哪个脚本/样式标签,并删除相应的标签:

http://plnkr.co/edit/5fCUV6WDxoLZ8kk9NSxb?p=preview

// Code goes here
angular.module("myApp", []).directive("styleSheetLoader", function(){
  function loadjscssfile(filename, filetype){
   if (filetype=="js"){ //if filename is a external JavaScript file
    var fileref=document.createElement('script')
    fileref.setAttribute("type","text/javascript")
    fileref.setAttribute("src", filename)
   }
   else if (filetype=="css"){ //if filename is an external CSS file
    var fileref=document.createElement("link")
    fileref.setAttribute("rel", "stylesheet")
    fileref.setAttribute("type", "text/css")
    fileref.setAttribute("href", filename)
   }
   if (typeof fileref!="undefined")
    document.getElementsByTagName("head")[0].appendChild(fileref)
  }
  return {
    restrict:"E",
    scope: {condition:"@", cssFile:"@"},
    link: function(scope, iElem, iAttrs) {
      console.log(iAttrs.condition);
      if(iAttrs.condition)
      {
        console.log("here", iAttrs.cssFile)
        loadjscssfile(iAttrs.cssFile, "css");
      }
      iAttrs.$observe("condition", function(){
        if(iAttrs.condition)
        {
          console.log("here", iAttrs.cssFile)
          loadjscssfile(iAttrs.cssFile, "css");
        }
      })
    }
  }
})

使用了此处引用的函数:http://www.javascriptkit.com/javatutors/loadjavascriptcss.shtml

Edit在plunkr中添加了一些零件,以删除我在添加新零件之前创建的工厂添加的其他样式表,这并不完美,但它可以工作。