Leon's Blogging

Coding blogging for hackers.

Angular Custom Directive

| Comments

在 angular 當中可以自己客製 Directive,讓 code 變得更乾淨。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
app.directive('productTitle', function(){
  return{
      restrict: 'E'
      templateUrl: 'product-title.html'
  }
});

<product-title></product-title>

app.directive('productTitle', function(){
  return{
      restrict: 'A'
      templateUrl: 'product-title.html'
  }
});

//js 的 productTitle 名稱在 html 就會變成 product-title
<h3 product-title></h3>

A  Attribute (You want to use your directive as <div rating>)
E  Element (Use it as <rating>)
C  Class. (Use it like <div class=rating>)
M  Comment (Use it like <! directive: rating >

controller 一起包在 app.directive 裡面

1
2
3
4
5
6
7
8
9
10
11
12
13
app.directive('productTitle', function(){
  return{
      restrict: 'A'
      templateUrl: 'product-title.html'
      controller: function() {
          this.tab = 1;
          },
      controllerAs: "tab"
  }
});

//js 的 productTitle 名稱在 html 就會變成 product-title
<h3 product-title></h3>

參考文件:
入門AngularJS筆記-directive
自訂 AngularJs Directive (1) :開始
自訂 AngularJs Directive (2): Hello World

Comments