Angular JS (指令 directive)

來源:互聯網
上載者:User

標籤:style   color   io   java   ar   strong   div   sp   cti   

一,指令的建立

/*--Js code--*/
var app = angular.module("superhero",[]);
app.directive("superman",function(){
return {
  restrict: "E",
  template: "<div> Here I am to save the day </div>"
}

})

/*--HTML code--*/
<div ng-app="superhero">
  <superman></superman>
</div>

這樣可以建立一個指令。

二,指令的限制
restrict: "A", 表示指令是 對於 "attribute(屬性)", restrict: "E", 表示指令是 對於 "Element(元素)",
再舉一個例子:
/*--HTML code--*/
<div ng-app="superhero">
   <div superman flash></div>
</div>

/*--Javascript code--*/
var app = angular.module("superhero",[]);
app.directive("superman",function(){
  return{
    restrict:"A",
    link:function(){
      alert("I am ok");
    }
  }
});
app.directive("flash",function(){
  return{
    restrict:"A",
    link:function(){
      alert("I am ok 222")
    }
  }
})

上面的例子不是Dom元素的修改,而是產生一個alert function.

三。基本行為
我們也可以添加一些方法:
/*--HTML code--*/
<div ng-app="behaviorApp">
  <div enter leave>I‘m content</div>
</div>
/*--Javascript code--*/
var app = angular.module("behaviorApp", [])

app.directive("enter", function(){
 return function(scope, element) {
      element.bind("mouseenter", function(){
        console.log("I‘m inside of you!");
      })
    }
});

app.directive("leave", function(){
 return function(scope, element) {
      element.bind("mouseleave", function(){
        console.log("I‘m leaving on a jet plane!");
      })
    }
});

我們可以為這個指令添加了兩個事件。

Angular JS (指令 directive)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.