AngularJS - Directive/Controller

Resume

In this passage, we will talk about Directive and Controller.


Directive

First of all, we will concentrate on Directive. In AngularJS, we can create our own HTML Tag/Element name, Attribute and even Comment.

Create Tag/Element name

In the following codes, we can see how we can create our own HTML Tag/Element name.

<body ng-app="app">
    <my-own-tag></my-own-tag>
    <script>
        angular.module("app",[]).directive("myOwnTag",function(){
            return {
                restrict : "E",
                    template : "<h1>Hello, World!</h1>"
            };
        });
</body>

The code above will show "Hello, World!" in h1 style
In this example, we can notice that, we have created a new HTML Tag/Element name, and appended a h1 DOM to <my-own-tag> .
Secondly, even our tag is <my-own-tag>, we should use myOwnTag while binding our tag in AngularJS.

Attention: After appending an element to an Directive, we cannot append another element to the previous element using AngularJS
The following code DOESN’T work

var app = angular.module("app", []);
app.directive("my-own-tag", function () {
    return {
        restrict: "E",
        template: "<title></title>",
    }
});

app.directive("title", function () {
    return {
        restrict: "E",
        template:"<h1>Title</h1>",
    }
});

<h1>Title</h1> Will be escaped and become &lt;h1&gt;Title&lt;/h1&gt;

Restrict

Maybe some people have noticed that we have used restrict while returning. Well, in fact we can restrict our Directive to only be invoked by some of the methods.
We have 4 different property to do that.
restrict : "E" for Element name / Tag
restrict : "A" for Attribute
restrict : "C" for Class
restrict : "M" for Comment.
Also, we can have combined restriction such as:
restrict : "MC".

Others

We can also use the method above for other things.

<div my-own-attr></div my-own-attr>
<div class="my-own-class"></div class="my-own-class">

or even in comments

<!-- directive : my-own-comment -->

All these methods work and have the same effect as tag do.


Controller

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值