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 相关文章推荐
JQuery实现自定义对话框的代码
Jun 15 Javascript
javascript自执行函数之伪命名空间封装法
Dec 25 Javascript
JS正则表达式大全(整理详细且实用)
Nov 14 Javascript
使用JQ来编写最基本的淡入淡出效果附演示动画
Oct 31 Javascript
jQuery Validate插件实现表单强大的验证功能
Dec 18 Javascript
JavaScript toUpperCase()方法使用详解
Aug 26 Javascript
原生js更改css样式的两种方式
Mar 15 Javascript
基于vue 添加axios组件,解决post传参数为null的问题
Mar 05 Javascript
Vue中通过Vue.extend动态创建实例的方法
Aug 13 Javascript
Vue路由守卫之路由独享守卫
Sep 25 Javascript
JS控制GIF图片的停止与显示
Oct 24 Javascript
JavaScript中EventBus实现对象之间通信
Oct 18 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
第六节--访问属性和方法
2006/11/16 PHP
让你的网站首页自动选择语言转跳
2006/12/06 PHP
PHP获取youku视频真实flv文件地址的方法
2014/12/23 PHP
YII Framework框架教程之日志用法详解
2016/03/14 PHP
基于JQuery的多标签实现代码
2012/09/19 Javascript
JS中 用户登录系统的解决办法
2013/04/15 Javascript
Javascript中call与apply的学习笔记
2014/09/22 Javascript
JS跨域问题详解
2014/11/25 Javascript
js中键盘事件实例简析
2015/01/10 Javascript
$.extend 的一个小问题
2015/06/18 Javascript
jQuery原型属性和原型方法详解
2015/07/07 Javascript
使用Script元素发送JSONP请求的方法
2016/06/12 Javascript
值得分享的JavaScript实现图片轮播组件
2016/11/21 Javascript
利用ECharts.js画K线图的方法示例
2018/01/10 Javascript
微信小程序dom操作的替代思路实例分析
2018/12/06 Javascript
VUE单页面切换动画代码(全网最好的切换效果)
2019/10/31 Javascript
浅谈vue中组件绑定事件时是否加.native
2019/11/09 Javascript
教你如何在Django 1.6中正确使用 Signal
2014/06/22 Python
将Python代码打包为jar软件的简单方法
2015/08/04 Python
python使用matplotlib绘制折线图教程
2017/02/08 Python
Python内置函数delattr的具体用法
2017/11/23 Python
python跳过第一行快速读取文件内容的实例
2018/07/12 Python
利用python实现汉字转拼音的2种方法
2019/08/12 Python
python 中值滤波,椒盐去噪,图片增强实例
2019/12/18 Python
Python tkinter三种布局实例详解
2020/01/06 Python
使用Python第三方库pygame写个贪吃蛇小游戏
2020/03/06 Python
在 Pycharm 安装使用black的方法详解
2020/04/02 Python
pandas数据处理之绘图的实现
2020/06/15 Python
CSS3实现自定义Checkbox特效实例代码
2017/04/24 HTML / CSS
外语专业毕业生自我评价分享
2013/10/05 职场文书
小学生保护环境倡议书
2014/05/15 职场文书
采购员岗位职责
2015/02/03 职场文书
2015年城乡环境综合治理工作总结
2015/07/24 职场文书
详解Apache SkyWalking 告警配置指南
2021/04/22 Servers
详解Python中的进程和线程
2021/06/23 Python
postgresql如何找到表中重复数据的行并删除
2023/05/08 MySQL