scope 作用域
1 | <h1 click-me>{{name}}</h1> |
1 | <script> |
使用 scope: {} 即给指令创建自己的作用域
1 | app.directive('clickMe',[function(){ |
使用 controller 属性可改变 scope 指向
scope 通讯,directive 中的 model 改变,controller 中的 model 跟着变
1 | <div ng-controller="TestCtrl"> |
1 | app.controller('TestCtrl', ['$scope', function($scope) { |
&、=、@ 的区别
1 | <div ng-controller="TestCtrl"> |
1 | <script type="text/javascript"> |
= 用于绑定 controller 中的变量,
@ 获取属性的字面量值
& 绑定 function
require 属性
简单的理解,require 用于请求另外的 controller,传入当前 directive 的 linking function 中
简单例子:
html
1 | <div ng-controller="TestCtrl"> |
controller
1 | app.controller('TestCtrl', ['$scope', function($scope) { |
directive
1 | app.directive('add', [function() { |
ngModel前可以使用 ?^ 两个前缀
? - 不要抛出异常。这使这个依赖变为一个可选项
^ - 允许查找父元素的controller
ngModelCtrl.$setViewValue 可改变 controller 中 ng-model 的值
自定义表单验证 $setValidity
1 | .has-error{ |
1 | <div ng-controller="TestCtrl"> |
1 | app.controller('TestCtrl', ['$scope', function($scope) { |
首先需要将默认的表单验证禁止 novalidate,设置 form 的 name 字段能让 controller 中通过 $scope.form 取到表单
在 username 字段中自定义验证规则 custom-rule,然后在 customRule 指令中规定只有输入为 xwill 时,表单才可用
在 controller 中可以使用 form.$invalid 判断表单是否可用,form.username.$invalid 判断某字段是否可用
$formatters 和 $parses
1 | <div ng-controller="TestCtrl"> |
1 | app.controller('TestCtrl', ['$scope', function($scope) {}]); |
这两个方法常用于输入小写,强制转为大写;输入负数转为0,等等~
$formatters 和 $parses 的区别