通常我们这样定义个module并随之定义一个controller.

var app = angular.module('myApp', []);

app.controller('CustomersController', ['$scope', function($scope){
var counter = 0; $scope.customer = {
name:'',
street:''
}; $scope.customers = [
{
name:'',
street:''
},
...
]; $scope.addCustomer = function(){
counter++;
$scope.customers.push({
name:'' + counter,
street: coutner + ''
}); $scope.changeData = function(){
counter++;
$scope.customer = {
name: '',
street:counter + ''
};
}
}
}]);

■ 使用ng-include引用子视图

在一个子视图中可以使用CustomersController,子视图的名称是:child.html

Name:{{customer.Name}}
Street:{{customer.street}}

然后在一个主视图中比如是index.html使用子视图:

<div ng-include="child.html"></div>

■ 初识自定义directive

如果使用自定义directive也可以做到。

angular.module('myApp').directive('myInfo', function(){
return{
template:'Name:{customer.name}<br/>Street:{{customer.street}}'
};
})

在index.html主视图中可以这样使用自定义的directive。

<div my-info></div>

为什么myInfo到了视图中变成了my-info?这是一个惯例,比如我们经常用到的ng-repeat,在AngularJS中的源代码中是ngRepeat。还有,为什么,自定义的名称为myInfo的directive可以使用CustomersController的scope呢?因为主视图index.html中使用了CustomersController,而同在index.html视图中的<div my-info></div>共享了CustomersController的scope。

directive通常的用法包括如下:

angular.module('modulename')
.directive('myDirective', function(){
return {
restrict: 'EA', //E表示element, A表示attribute,C表示class,M表示commnent,即注释
scope:{
title: '@' //@读属性值,=双向绑定,&用户函数
}
template: '<div>{{myVal}}</div>',
templateUrl: 'app/sample.html',
controller: 'myController',
link:function($scope, element, attrs){}//DOM操作
};
})

■ 自定义direcitve操作DOM元素

app.directive('myDomDirective', function(){
return {
link: function($scope, ele, attrs){
ele.bind('click', function(){
ele.html('');
}); ele.bind('mouseenter', function(){
ele.css('background-color','red');
}); ele.bind('mouseleave', function(){
ele.css('background-color','white');
});
}
};
});

在页面中这样使用:

<div my-dom-directive></div>

■ 封闭自定义directive的scope

默认情况下,自定义的directive的会共享父scope,但是,有时候我们希望自定义的directive的scope是封闭的、独立的,比如希望自定义的direcitve被用在多处。

只需要加上scope属性就好了,如下:

angular.module('myDirecitve', function(){
return {
scope:{},
template: ''
}
});

scope属性接受一个对象,在该对象中可以定义独立scope内的属性,而属性值的写法有三种,分别是@,=,&

● 使用@,外部scope赋值不影响封闭scope中的变量

angular.module('myApp').directive('myIsolateScopeWithName', function(){
return {
scope:{
name: '@'
},
template: 'Name:{{name}}',
controller: 'MyController'
};
});

在封闭的scope中定义了一个name变量,占位符@表示这里接受一个值。

如何给这里的变量赋值呢?

一种是把name成为一个属性来接收值:

<div my-isolated-scope-with-name name="{{ customer.name }}"></div>

一种是在MyController中给name赋值:

$scope.name = '';

如果把name="{{ customer.name }}"改成myname="{{ customer.name }}"呢?

那就需要这样定义:

angular.module('myApp').directive('myIsolateScopeWithName', function(){
return {
scope:{
name: '@myname'
},
template: 'Name:{{name}}',
controller: 'MyController'
};
});

● 使用=,外部scope赋值会影响封闭scope中的变量

angular.module('myApp').directive('myIsolateScopeWithEqual', function(){
return {
scope:{
customer: '='
},
template: '<ul><li ng-repeate="prop in customer">{{prop}}</li></ul>'
};
});

注意,这里的customer是作为变量在使用,而不是{{customer}},一旦外部的赋值发生变化会影响独立scope中的customer变量值。同样,一旦独立scope中的customer值发生变化,也会影响外部的scope的customer属性值。

外部这样使用:

<div my-isolated-scope-with-equal customer="customer"></div>

● 使用&,允许外部scope传递一个函数给封闭scope

angular.module('myApp').directive('myIsolateScopeWithFunction', function(){
return {
scope: {
datasource: '=',
action:'&'
},
template: '<ul><li ng-repeat="prop in datasource">{{ prop }}</li></ul> ' + '<button ng-click="action()">Change Data</button>'
};
});

这样使用这个directive

<div my-isolated-scope-with-function
datasource="customer"
action="changeData()">
</div>

changeData方法被定义在了controller里面:

$scope.changeData = function () {
counter++;
$scope.customer = {
name: 'James',
street: counter + ' Cedar Point St.'
};
};

如何让外部scope传递一个带参函数给封闭scope呢?

angular.module('directivesModule').directive('isolatedScopeWithController', function () {
return {
restrict: 'EA',
scope: {
datasource: '=',
add: '&',
},
controller: function ($scope) {
... $scope.addCustomer = function () {
//Call external scope's function
var name = 'New Customer Added by Directive';
$scope.add({ name: name }); //Add new customer to directive scope
$scope.customers.push({
name: name,
street: counter + ' Main St.'
});
};
},
template: '<button ng-click="addCustomer()">Change Data</button>' +
'<ul><li ng-repeat="cust in customers">{{ cust.name }}</li></ul>'
};
});

在页面中这样调用:

<div isolated-scope-with-controller datasource="customers" add="addCustomer(name)"></div>

■ 允许自定义的direcitve被嵌套

只要把tranclude设置成true就可以。

"use strict";

angular.module("psFramework").directive("psFramework",function(){
return {
transclude: true,
scope:{
title: '@',
subtitle:'@',
iconFile:'@'
},
controller: "psFrameworkController",
templateUrl: "ext-modules/psFramework/psFrameworkTemplate.html"
};
})

然后在页面中就可以这样使用:

<ps-framework title="", subtile="", icon-file="">
<ps-menu>
...
</ps-menu>
</ps-framework>

参考:https://weblogs.asp.net/dwahlin/

AngularJS自定义Directive初体验的更多相关文章

  1. vue.js2.0 自定义组件初体验

    理解 组件(Component)是 Vue.js 最强大的功能之一.组件可以扩展 HTML 元素,封装可重用的代码.在较高层面上,组件是自定义元素, Vue.js 的编译器为它添加特殊功能.在有些情况 ...

  2. AngularJS自定义Directive中link和controller的区别

    在AngularJS中,自定义Directive过程中,有时用link和controller都能实现相同的功能.那么,两者有什么区别呢? 使用link函数的Directive 页面大致是: <b ...

  3. AngularJS自定义Directive不一定返回对象

    AngularJS中,当需要自定义Directive时,通常返回一个对象,就像如下的写法: angular.module('modulename') .directive('myDirective', ...

  4. AngularJS自定义Directive

    (编辑完这篇之后,发现本篇内容应该属于AngularJS的进阶,内容有点多,有几个例子偷懒直接用了官方的Demo稍加了一些注释,敬请见谅). 前面一篇介绍了各种常用的AngularJS内建的Direc ...

  5. AngularJS自定义Directive与controller的交互

    有时候,自定义的Directive中需要调用controller中的方法,即Directive与controller有一定的耦合度. 比如有如下的一个controller: app.controlle ...

  6. angularJs初体验,实现双向数据绑定!使用体会:比较爽

    使用初体验:ng 双向数据绑定: 最简单的双向数据绑定:(使用默认模块控制) <body ng-app> <input type="text" ng-model= ...

  7. 理解AngularJS生命周期:利用ng-repeat动态解析自定义directive

    ng-repeat是AngularJS中一个非常重要和有意思的directive,常见的用法之一是将某种自定义directive和ng-repeat一起使用,循环地来渲染开发者所需要的组件.比如现在有 ...

  8. AngularJs中,如何在父元素中调用子元素为自定义Directive中定义的函数?

    最近一段时间准备使用AngularJs中的自定义Directive重构一下代码. 在这里说明一下,把自定义控件封装成Directive并不一定是要复用,而是要让代码结构更加清晰.就好像你将一个长方法拆 ...

  9. 前端angularJS利用directive实现移动端自定义软键盘的方法

    最近公司项目的需求上要求我们iPad项目上一些需要输入数字的地方用我们自定义的软键盘而不是移动端设备自带的键盘,刚接到需求有点懵,因为之前没有做过,后来理了一下思路发现这东西也就那样.先看一下实现之后 ...

随机推荐

  1. 运动规划——PT and PVT 模式

    最近项目成员在做机器人上层开发时,经常说到PT模式和PVT模式.一直没搞懂这两种模式的实际差别.上网检索进行学习...... ref link:https://blog.csdn.net/m0_376 ...

  2. 基于Consul的数据库高可用架构【转】

    几个月没有更新博客了,已经长草了,特意来除草.本次主要分享如何利用consul来实现redis以及mysql的高可用.以前的公司mysql是单机单实例,高可用MHA加vip就能搞定,新公司mysql是 ...

  3. maven:多个镜像配置

    <mirrors> <mirror> <id>nexus-aliyun</id> <mirrorOf>nexus-aliyun</mi ...

  4. Spring Cloud与Docker微服务架构实战 PDF

    电子版百度云下载 链接: https://pan.baidu.com/s/115u011CJ8MZzJx_NqutyTQ 提取码: 关注公众号[GitHubCN]回复2019获取 本书的代码 共计70 ...

  5. 利用openssl构建根证书-服务器证书-客户证书

    利用openssl构建根证书-服务器证书-客户证书 OpenSSL功能远胜于KeyTool,可用于根证书,服务器证书和客户证书的管理 一.构建根证书 1.构建根证书前,需要构建随机数文件(.rand) ...

  6. Windows下调用caffe的matlab接口

    一.编译caffe的matlab接口 在我的这篇博客windows-caffe配置已经说了怎么编译了,这里就略过了. 编译成功后,会得到如下图所示文件: matlab接口就在matcaffe文件夹里. ...

  7. 链表用途&&数组效率&&链表效率&&链表优缺点

    三大数据结构的实现方式 数据结构 实现方式 栈  数组/单链表 队列  数组/双端链表 优先级队列 数组/堆/有序链表 双端队列 双向链表 数组与链表实现方式的比较 数组与链表都很快 如果能精确预测栈 ...

  8. flask 中的request

    request.args                    从URL地址中的参数request.form                   POST请求时 从FormData中获取参数reque ...

  9. NOIP练习赛题目1

    有些题目可能没做,如计算几何.恶心模拟. 高级打字机 难度级别:C: 运行时间限制:1000ms: 运行空间限制:51200KB: 代码长度限制:2000000B 试题描述 早苗入手了最新的高级打字机 ...

  10. MVVM模式下关闭窗口的实现

    通过行为来实现 实现界面与逻辑的分离 窗口关闭行为:其中含有布尔型的Close属性,将相应的关闭行为绑定到该属性上,则可以实现窗口的关闭行为,从而实现VM与View的分离 public class W ...