angularjs自定义ng-model标签的属性


Posted in Javascript onJanuary 21, 2016

有的时候我们需要为非input类型的元素添加ng-model来实现双向的数据绑定,从而减少冗余代码,那么可以尝试一下的方式

例如:我页面中使用了contenteditable这个属性来实现用户可直接编译的div元素

html:

<style>
    .text{
      margin:0 auto;
      width:100px;
      height:50px;
      border:1px solid red;
    }
  </style>
</head>
<body>
<div ng-controller="selectController">
  <div ng-repeat="pop in citylist">
    <div class="text" contenteditable="true" ng-model="pop.pop"></div>
  </div>
  <button ng-click="cs()">输出新数据</button>
</div>
</body>

但是直接绑定ng-model是肯定得不到数据的,这时就需要为其增加自定义的属性,如下所示。

js:

<script>
  var app = angular.module('app', []);
  app.controller('selectController', function ($scope) {
    $scope.citylist=[{id:1,pop:"北京"},{id:1,pop:"上海"},{id:1,pop:"广州"}];
    $scope.p={};
    $scope.cs=function(){
      console.log($scope.citylist);
    }
  }).directive('contenteditable', function() {//自定义ngModel的属性可以用在div等其他元素中
    return {
      restrict: 'A', // 作为属性使用
      require: '?ngModel', // 此指令所代替的函数
      link: function(scope, element, attrs, ngModel) {
        if (!ngModel) {
          return;
        } // do nothing if no ng-model
        // Specify how UI should be updated
        ngModel.$render = function() {
          element.html(ngModel.$viewValue || '');
        };
        // Listen for change events to enable binding
        element.on('blur keyup change', function() {
          scope.$apply(readViewText);
        });
        // No need to initialize, AngularJS will initialize the text based on ng-model attribute
        // Write data to the model
        function readViewText() {
          var html = element.html();
          // When we clear the content editable the browser leaves a <br> behind
          // If strip-br attribute is provided then we strip this out
          if (attrs.stripBr && html === '<br>') {
            html = '';
          }
          ngModel.$setViewValue(html);
        }
      }
    };
  })
</script>

其中参数类别如下:

angularjs自定义ng-model标签的属性

部分参数解释

restrict:

(字符串)可选参数,指明指令在DOM里面以什么形式被声明;

取值有:E(元素),A(属性),C(类),M(注释),其中默认值为A;

E(元素):<directiveName></directiveName>
A(属性):<div directiveName='expression'></div>
C(类):   <div class='directiveName'></div>
M(注释):<--directive:directiveName expression-->

2.require

字符串代表另一个指令的名字,它将会作为link函数的第四个参数

具体用法我们可以举个例子说明

假设现在我们要编写两个指令,两个指令中的link链接函数中(link函数后面会讲)存在有很多重合的方法,

这时候我们就可以将这些重复的方法写在第三个指令的controller中(上面也讲到controller经常用来提供指令间的复用行为)

然后在这两个指令中,require这个拥有controller字段的的指令(第三个指令),

最后通过link链接函数的第四个参数就可以引用这些重合的方法了。

<!doctype html>
<html ng-app="myApp">
<head>
 <script src="http://cdn.staticfile.org/angular.js/1.2.10/angular.min.js"></script>
</head>
<body>
 <outer-directive>
   <inner-directive></inner-directive>
   <inner-directive2></inner-directive2>
 </outer-directive>
 <script>
  var app = angular.module('myApp', []);
  app.directive('outerDirective', function() {
     return {
        scope: {},
        restrict: 'AE',
        controller: function($scope) {   
         this.say = function(someDirective) { 
           console.log('Got:' + someDirective.message);
         };
        }
      };
  });
  app.directive('innerDirective', function() {
     return {
        scope: {},
        restrict: 'AE',
        require: '^outerDirective',
        link: function(scope, elem, attrs, controllerInstance) {
            scope.message = "Hi,leifeng";
            controllerInstance.say(scope);
        }
     };
  });
  app.directive('innerDirective2', function() {
     return {
        scope: {},
        restrict: 'AE',
        require: '^outerDirective',
        link: function(scope, elem, attrs, controllerInstance) {
            scope.message = "Hi,shushu";
            controllerInstance.say(scope);
        }
     };
  });
 </script>
</body>
</html>

上面例子中的指令innerDirective和指令innerDirective2复用了定义在指令outerDirective的controller中的方法

也进一步说明了,指令中的controller是用来让不同指令间通信用的。

另外我们可以在require的参数值加上下面的某个前缀,这会改变查找控制器的行为:

(1)没有前缀,指令会在自身提供的控制器中进行查找,如果找不到任何控制器,则会抛出一个error

(2)?如果在当前的指令没有找到所需的控制器,则会将null传给link连接函数的第四个参数

(3)^如果在当前的指令没有找到所需的控制器,则会查找父元素的控制器

(4)?^组合

Javascript 相关文章推荐
ASP中用Join和Array,可以加快字符连接速度的代码
Aug 22 Javascript
js日期联动示例
May 02 Javascript
js单词形式的运算符
May 06 Javascript
JavaScript函数的调用以及参数传递
Oct 21 Javascript
noty ? jQuery通知插件全面解析
May 18 Javascript
AngularJS模板加载用法详解
Nov 04 Javascript
node.js支持多用户web终端实现及安全方案
Nov 29 Javascript
微信小程序支付前端源码
Aug 29 Javascript
Vue动态组件与异步组件实例详解
Feb 23 Javascript
浅入深出Vue之自动化路由
Aug 06 Javascript
如何基于javascript实现贪吃蛇游戏
Feb 09 Javascript
Vant+postcss-pxtorem 实现浏览器适配功能
Feb 05 Javascript
angularjs在ng-repeat中使用ng-model遇到的问题
Jan 21 #Javascript
js实现的二分查找算法实例
Jan 21 #Javascript
jQuery模拟物体自由落体运动(附演示与demo源码下载)
Jan 21 #Javascript
angularjs表格分页功能详解
Jan 21 #Javascript
使用angularjs创建简单表格
Jan 21 #Javascript
Jquery中巧用Ajax的beforeSend方法
Jan 20 #Javascript
Javascript中神奇的this
Jan 20 #Javascript
You might like
PHP扩展开发入门教程
2015/02/26 PHP
php中Snoopy类用法实例
2015/06/19 PHP
详解Yii2 rules 的验证规则
2016/12/02 PHP
Laravel 实现密码重置功能
2018/02/23 PHP
Yii框架 session 数据库存储操作方法示例
2019/11/18 PHP
FireFox与IE 下js兼容触发click事件的代码
2008/11/20 Javascript
dojo随手记 gird组件引用
2011/02/24 Javascript
基于jquery实现后台左侧菜单点击上下滑动显示
2013/04/11 Javascript
快速解决jquery之get缓存问题的最简单方法介绍
2013/12/19 Javascript
JS 获取浏览器和屏幕宽高等信息代码
2014/03/31 Javascript
超级简单的jquery操作表格方法
2014/12/15 Javascript
js鼠标滑过图片震动特效的方法
2015/02/17 Javascript
js跨域请求数据的3种常用的方法
2015/12/01 Javascript
jQuery取消特定的click事件
2016/02/29 Javascript
关于javascript事件响应的基础语法总结(必看篇)
2016/12/26 Javascript
vue.js移动数组位置,同时更新视图的方法
2018/03/08 Javascript
ES6中的迭代器、Generator函数及Generator函数的异步操作方法
2019/05/12 Javascript
vue自定义指令限制输入框输入值的步骤与完整代码
2020/08/30 Javascript
[01:12](回顾)DOTA2国际邀请赛,全世界DOTAer的盛宴
2014/07/01 DOTA
[35:55]完美世界DOTA2联赛PWL S3 Rebirth vs CPG 第一场 12.11
2020/12/13 DOTA
python正则匹配查询港澳通行证办理进度示例分享
2013/12/27 Python
使用IPython下的Net-SNMP来管理类UNIX系统的教程
2015/04/15 Python
Python中用函数作为返回值和实现闭包的教程
2015/04/27 Python
flask中的wtforms使用方法
2018/07/21 Python
Python3.6简单的操作Mysql数据库的三个实例
2018/10/17 Python
python-itchat 统计微信群、好友数量,及原始消息数据的实例
2019/02/21 Python
Python&amp;&amp;GDAL实现NDVI的计算方式
2020/01/09 Python
html5中嵌入视频自动播放的问题解决
2020/05/25 HTML / CSS
全球领先的全景影像品牌:Insta360
2019/08/21 全球购物
铭万公司.net面试题笔试题
2014/07/20 面试题
高级电工工作职责
2013/11/21 职场文书
陈欧广告词
2014/03/14 职场文书
捐书活动总结
2014/05/04 职场文书
法人代表任命书范本
2014/06/05 职场文书
2014年企业党支部工作总结
2014/12/04 职场文书
Python还能这么玩之只用30行代码从excel提取个人值班表
2021/06/05 Python