如何理解Angular之指令

來源:互聯網
上載者:User

標籤:

今天給大家分享一些我學習Angular的總結,這篇文章是關於指令的。

1.指令的定義

 

從使用者的角度來看,指令就是在應用的模板中使用的自訂HTML標籤。指令可以很簡單,也可以很複雜。AngularJS的HTML編譯器會解析指令,增強模板的功能。也是組件化未來的發展趨勢,目前HTML5中也加入了很多新標籤,但是在實際業務開發過程中,有很多複用的模板,加上複用的互動效果,可以將其編寫為AngularJS的指令,開發工程師可以在同一個項目,或多重專案中使用,實現開發一次,到處使用的目標。

 

2.內建指令和自訂指令

 

AngularJS內部指令都是ng-diretivename這種,以ng-開頭。可以通過 https://docs.angularjs.org/api/ng/directive
查看AngularJS的指令。在實際開發中,常用的有以下幾個:

ngApp

ngController

ngClass

ngClick

ngShow和ng-hide

ngRepeat

ngSubmit

 

3.第一個指令

 

編寫一個第一個指令,輸出Hello AngularJS Diretive.

index.html

<html ng-app="app">

<head><title>AngularJs First Diretive</title>

  <linkrel="stylesheet"href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"></link>

  <linkrel="stylesheet"href="http://maxcdn.bootstrapcdn.com/bootswatch/3.3.5/cosmo/bootstrap.min.css" />

  <linkrel="stylesheet"href="http://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css" />

   <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.js"></script>

  <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>

  <script src="https://code.angularjs.org/1.5.7/angular.js"></script>

  <script src="script.js"></script></head>

<body ng-controller="mainCtrl">

  <hello-world></hello-world></body>

</html>

script.js

var app=angular.module(’app’,[]);app.controller(’mainCtrl’,function($scope){

  $scope.message="Learning Angularjs";

 

});

angular.module(’app’).directive(’userInfoCard’,function(){

  return {

    template:"Hello World. I am an Angularjs Diretive.",

    restrict:"EA",

    replace:true

  }})

運行效果如下:

1.總結

 

在AngularJS中,指令非常的重要。指令是AngularJS和其他大多數JavaScript用戶端架構的區別所在,也是未來Web開發組件化趨勢所在。有了指令,無需編輯一大段代碼定義模型;有了指令,AngularJS的模型和視圖得到了建好,從而讓開發人員可以快速高效的開發強大的應用。

 

原文來自:部落格園/快樂八哥

如何理解Angular之指令

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.