理解指令的restrict属性(转)
生活随笔
收集整理的這篇文章主要介紹了
理解指令的restrict属性(转)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
restrcit屬性說明
restrict: EACM中的任意一個之母。它是用來限制指令的聲明格式的。
E - 元素名稱:<my-directive></my-directive> A - 屬性: <div my-directive="exp"> </div> C - 類名:<div class="my-directive: exp;"></div> M - 注釋: <!-- directive: my-directive exp -->
它做了什么
示例
<html ng-app='app'>
<body>
<hello> </hello>
<div hello> </div>
<div class="hello"> </div>
<!-- directive: hello -->
</body>
<script src="bower_components/angular/angular.js"></script>
<script>
var appModule = angular.module('app', []);
appModule.directive('hello', function() {
return {
restrict: 'AEC',
template: '<h3>Hi there</h3>',
replace: true
link:function(scope, elem, attrs){
console.log(elem);
//console.log(attrs);
}
};
});
</script>
</html>
運行結果
<h3>Hi there</h3> <h3 hello>Hi there</h3> <h3 class="hello">Hi there</h3> <h3>Hi there</h3>
可以看到幾種方式,做的事情一樣,只有部分地方不同. 這些區別有什么作用?
有何作用
restrict=E時,瀏覽器無法識別指令的聲明元素,則這個指令一定是起替換作用,也就是說template一定有值.
restrict=A時,它是以元素屬性存在的,那么這個指令的作用可以不是替換. 那么它可以做什么?以link方式操作dom.
比如在初始時為元素聚焦
<input type="input" focus/>
appModule.directive('focus', function() {
return {
restrict: 'A',
link:function(scope, elem, attrs){
$(elem).focus();
}
};
});
restrict=C,則是在綁定指令的同時,指定它的css樣式,讓指令與樣式同步.
restrict=M,則在一些場合非常有用,方便在注釋與代碼之間切換.
總結
以上是生活随笔為你收集整理的理解指令的restrict属性(转)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 网格布局每个网格都能放置一个组件_And
- 下一篇: android 前台服务自定义布局不显示