一,指令的建立app
/*--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.ide
三。基本行爲
咱們也能夠添加一些方法:
/*--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!");
element.addClass("active");
})
}
});
app.directive("leave", function(){
return function(scope, element) {
element.bind("mouseleave", function(){
console.log("I'm leaving on a jet plane!");
element.removeClass("active"); // 能夠進行樣式的控制
})
}
});
咱們能夠爲這個指令添加了兩個事件。spa
四. 用 attrs 重構一下
/*--HTML code--*/
<div ng-app="behaviorApp">
<div enter="panel" leave>I'm content</div>
</div>
/*--Javascript code--*/
var app = angular.module("behaviorApp", [])
app.directive("enter", function () {
return function (scope, element, attrs) {
element.bind("mouseenter", function () {
element.addClass(attrs.enter);
});
};
});
app.directive("leave", function () {
return function (scope, element, attrs) {
element.bind("mouseleave", function () {
element.removeClass(attrs.enter);
});
};
});
rest