首页 > 语言 > JavaScript > 正文

关于Angularjs中自定义指令一些有价值的细节和技巧小结

2024-05-06 15:19:49
字体:
来源:转载
供稿:网友

一:自定义指令常用模板

下面是大致的说明,不是全面的,后面来具体说明一些没有提及的细节和重要的相关知识:

angular.module('yelloxingApp', []).directive('uiDirective', function() {  return {      restrict:String,//标明该指令可以在模板中用于元素E、属性A、类C和注释M或组合        priority:Number,//设置指令执行优先级,在某个DOM上优先级高的会先执行        terminal:Boolean,        template:String or Template Function,//就是设置模板,和下面的templateUrl属性二个只可以设置一个,目的一样        templateUrl:String or Template Function,//除了字符串,这二个属性还可以设置函数        replace:Boolean,//指令模板是否替换原来的元素        scope:Boolean or Object,    controller:String or function(scope, element, attrs) { ... },        require:String or Array,        //你需要知道link在每个实例都执行一遍,compile全程只会执行一遍    link: function(scope, element, attrs,ctrl) { ... },        compile:function(element, attrs) {      //常用的就是compile的此处写执行一次的代码,或者在link方法里面写和dom有关的操作    }  };}); 

二:一些属性说明

【scope】

可以设置boolean或者对象,先来说说boolean,这个比较简单:

1.当设置true的时候,表示继承父scope,是一个子scope;

2.当设置false的时候,直接使用父scope。

还有一种对象设置方法,就是设置一种隔离的scope,在使用隔离scope的时候,提供了三种方法同隔离之外的地方交互,下面用一个例子来一一说明:

angular.module('yelloxingApp', []).directive("scopeExample", ['$rootScope', function($rootScope) {  return {    restrict: 'A',        scope: {      _userDataName: "=userDataName",      _onSend: "&onSend",      _fromName: "@fromName"    },        template: `      <button ng-click="_useParentMethod()">        点击按钮调用父级的方法      </button>            <input ng-model="_userDataName"/>      <ul>        <li>fromName={{newfromname}}</li>        <li>这是从父级获取到的{{_userDataName}}</li>      </ul>`,       link: function($scope, element, attrs) {      //使用@符号可将本地作用域的变量与DOM属性的值进行绑定,即这里通过@得到父类fromName的值      $scope.newfromname = $scope._fromName;      $scope._useParentMethod = function() {              //使用&符号可以在其中调用父类的方法        $scope._onSend({ "email": { "email": "yelloxing@gmail.com" } });        console.log($scope._userDataName);              };    }  };}]);

上面是指令的写法,下面来看看控制器里面有什么:

$scope.name = "心叶";$scope.user = "yelloxing";$scope.sendMail = function(email){  console.error(email);}            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选