AngularJS 指令入门
指令是运行在特定 dom 元素上的函数,用来扩展元素的功能。 一个简版的 directive 的形式是这样的 app.directive('myDirective',myDirective); myDirective.$inject = []; function myDirective(){ return { restrict: "AE",template: '' scope: {},link: function(){} } } 下面介绍一些常用的选项。 选项restrict(String)表示指令在 dom 中以何种形式被声明
属性(E)是最常用的声明指令方式,因为能兼容老版本IE,且不引入新标签。元素(A)方式适合创建一个完全独立、完整的组件。 priority(Number)指令优先级,默认为 0(最高1000,比如 ng-repeat ),如果需要同一元素上一个指令比另一个指令先被调用,可给它设置更高的优先级。 在 Angular 1.2 里面,如果使用 checkbox,同时绑定 <input type="checkbox" ng-model="formData.status" ng-click="check()"> $scope.check = function(){ if($scope.formData.status){ alert('true'); }else{ alert('false'); } } 会发现, template 和 templateUrl(String || Function)HTML 模版文件。 在调用指令后,模版文件是通过 XHR 来加载的,加载后会缓存到 $templateCache 服务中。 通过 AJAX 异步加载大量的模版会拖慢一个 Angular 应用的速度。可以提前将模版缓存到一个定义模版的 js 文件中,或者在加载 <script id="pagerTpl" type="text/html"> <div>...</div> </script> template: document.querySelector('#pagerTpl').innerHTML transclude(Boolean)当指令定义的标签内部也有标签的时候,
replace(Boolean)
设置为 scope(Boolean || Object)
最常用的通过一个空对象 但大多时候并不会直接使用无数据的隔离作用域。有三种办法让内部的隔离作用域同外部的作用域进行数据绑定。 =
在元素中使用属性的方式为(不可以使用 {% raw %} <div my-directive age="age"></div> scope: { age: '=' } @使用 在元素中的使用方式为(有 {% raw %} <div my-directive my-name="{{name}}"></div> // 视图中的 - 连接的属性转换到指令定义中要使用驼峰式 scope: { name: '@myName' } &这是一个绑定函数方法的前缀标识符,通过 & 可以对父级作用域进行绑定,以便在其中运行函数。 在元素中的使用方式为: <div my-directive change="changeName()"></div> scope: { changeName: '&change' } 更详细的栗子参见 这篇文章 的讲解。 controller(String || Function)一般情况下不需要使用指令的 用 controller 的形式是这样的: controller: function($scope,$ele,$attrs,$transclude){ ... } require(String || Array)一般情况下不需要使用 编译 和 链接AngularJS 应用启动后,会经历两个阶段。一是编译阶段( 编译在编译阶段,AngularJS 会遍历整个 HTML 文档并根据 JavaScript 中的指令定义来处理页面上声明的指令。 编译阶段可以改变原始的
compile 函数形式: /** * Compile function * * @param tElem - template element * @param tAttrs - attributes of the template element */ function(tEle,tAttrs){ ... } 链接链接阶段完成作用域和 link 函数形式: /** * pre-link and post-link function * * @param scope - scope associated with this instance * @param iElem - instance element * @param iAttrs - attributes of the instance element */ function(scope,iElem,iAttrs,ctrl){ ... } 如果指令定义中有 两者区别
栗子举个简单的行内编辑的栗子,默认显示,双击可编辑。 directive 文件 app.directive('inlineEdit',inlineEdit); inlineEdit.$inject = ['$document']; function inlineEdit($document){ return { restrict: 'A',templateUrl: 'inline-edit.html',scope: { desc: '=ngModel' },link: function(scope,ele,attrs){ scope.isEdit = false; ele.on('dblclick',function(){ scope.isEdit = true; scope.$digest(); }) $document.on('click',function(evt){ var src = evt.srcElement || evt.target,parent = src.parentNode; if(parent.classList && parent.classList[0] == 'inline-container'){ return; } scope.isEdit = false; scope.$digest(); }) } } } template 文件 <div class="inline-container" ng-show="isEdit"> <input type="text" ng-model="desc"> </div> <div ng-if="!isEdit"> {{desc}} </div> 然后,可以这样使用 <div ng-model="desc" inline-edit></div> (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |