使用angularjs寫指令

來源:互聯網
上載者:User

標籤:angularjs directive

自己使用angular實現html中類似title的功能.

1)首先寫指令

    exports.define = function(md) {

                 //這個是寫的通用的安全使用apply的服務

                 md.factory(‘safeApply‘, function($rootScope){

return function(scope, fn){

var phase = scope.$root.$$phase;

if(phase == ‘$apply‘ || phase == ‘$digest‘){

if(fn && (typeof (fn) === ‘function‘)){

fn();

}

}else{

scope.$apply(fn);

}

}

});

md.directive(‘showTitleDiv‘,[‘safeApply‘,function(safeApply){

return{

restrict: ‘A‘,

templateUrl: ‘/showTitleDiv.html‘,

scope: {

divobj: ‘=‘

},

link:function(scope, element, attrs){

scope.$watch(‘divobj.top‘, function(){

safeApply(scope, function(){

  element.css({‘position‘: ‘absolute‘, 

‘top‘ : scope.divobj.top + ‘px‘, 

         ‘left‘: scope.divobj.left + ‘px‘,

‘color‘: ‘#cccccc‘,

‘width‘: scope.divobj.width + ‘px‘,

‘height‘: scope.divobj.height + ‘px‘,

‘background-color‘: ‘#FFF‘,

‘border‘: ‘1px solid #CCC‘,

 ‘overflow-y‘: ‘auto‘,

 ‘overflow-x‘: ‘hidden‘

  });

})

});

}//return

};

}]);

};

});


2)對應的模板

   <div ng-show="divobj.isShow">

<div>層裡面的內容...</div>

</div>


3)如何引入指令

      在你要調用的頁面上添加:<div show-title-div divobj="titlediv"></div>

    define(function(require){

              //引用js中定義的常量

 var PFConstants = require(‘./productConstants.js‘);

 var md = angular.module("xxx",[]);

             //引入指令

 require(‘./directives/showTitleDivdirective.js‘).define(md);

             md.controller(‘insureManageCtrl‘,function(){

            

             });

     });

 4)如何觸發指令:

                    $scope.showtitle = function(index){

                                 //修改層的top和left屬性值

 $scope.dutydiv ={

 top: $(‘#aa‘).position().top+(index*20),

 left: $(‘#aa‘).position().left,

 width: 350,

 height: 250,

 isShow: true

 };

 };

 

 $scope.hidetitle = function(){

 $scope.dutydiv ={

 top: 0,

 left: 0,

 width: 0,

 height:0,

 isShow: false

 };

 };


本文出自 “小李廣之部落格” 部落格,請務必保留此出處http://6817977.blog.51cto.com/6807977/1597093

使用angularjs寫指令

聯繫我們

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