---
title: "温故知新:Angular下的 directive"
author: "HYFY"
date: "2013-12-20T13:12:17Z"
tags: ["HTML", "JavaScript"]
categories: ["Web前端"]
slug: "angular-directive"
draft: false
lastmod: "2013-12-20T13:12:17Z"
id: 1992678
url: "https://hyfy.iteye.com/blog/1992678"
---

Angularjs directive Angularjs 提供的directive指令可以用来写自己的命令甚至标签。 用例子来说事吧：自定义指令example directive.html \[code="html"] TestDirective

\[/code] TestDirective.js \[code="javascript"] angular.module('myApp',\[]) .controller('TestDirectiveController',function($scope){ $scope.content = {'name':'LiMing','age':'12'}; }) .directive('example',function(){ return { restrict:'A' template:'Name:{{content.name}},Age:{{content.age}}'; } }); \[/code] 在这里面定义了名为example的directive，它是一个function,返回值是一个对象: restrict属性表明example要匹配的的是一个标签('E')还是标签中的一个属性('A'),如这里的html中将example用在了div中，因此example便成了div的一个属性，因此restrict返回的是A; template属性表明要填充到div中的内容。 打开网页运行后便在此div处显示出Name:LiMing,Age:12. 在强大一点，可以用angular的directive功能实现重复模板的复用。例子如下： directive.html \[code="html"] TestDirective

\[/code] info.html(要复用的模板) \[code="html"]

Hello{{peopelInfo.name}},你已经{{peopleInfo.age}}岁了。

\[/code] TestDirectiveController.js \[code="javascript"] angular.module('myApp',\[]) .controller('TestDirectiveController',function($scope){ $scope.LiMing = {'name':'LiMing','age':'12'}; $scope.WangYu = {'name':'WangYu','age':'14'}; }) .directive('example',function(){ return { restrict:'A', scope:{ peopleInfo:'=info' }, templateUrl:'info.html'; } }); \[/code] 这里scope中的内容表明了模板中的poepleInfo变量要被谁替代，在这里是被info取代，info在directive.html中可以看到分别代表着'LiMing'和'WangYu',这样替代后便绑定到了TestDirectiveController下的$scope对应的变量上。