在自定义angular指令时,其中有一个叫做require的字段,这个字段的作用是用于指令之间的相互交流。举个简单的例子,假如我们现在需要编写两 个指令,在linking函数中有很多重合的方法,为了避免重复自己(著名的dry原则),我们可以将这个重复的方法写在第三个指令的 controller中,然后在另外两个需要的指令中require这个拥有controller字段的指令,最后通过linking函数的第四个参数就可以引用这些重合的方法。代码的结构大致如下:

var app = angular.modeule('myapp',[]);
app.directive('common',function(){
return {
...
controller: function($scope){
this.method1 = function(){
};
this.method2 = function(){
},
}
});
app.directive('d1',function(){
require: '?^common',
link: function(scope,elem,attrs,common){
scope.method1 = common.method1;
..
},
当然,上面例子只是指令中controller用法的一种。虽然一般来说,使用controller字段的机会不是很多,但是想要写好angularjs的指令,这是必须要掌握的一点。
引用内置指令

angular.module('myapp')
.directive('spoint', function() {
return {
require: 'ngmodel',
link: function(scope, elm, attrs, ctrl) {
var fibonacci = [1, 2, 3, 5, 8, 13, 20, 40, 80];
ctrl.$parsers.unshift(function(viewvalue) {
if (fibonacci.indexof(parseint(viewvalue)) >= 0) {
ctrl.$setvalidity('fibonacci', true);
return viewvalue;
} else {
ctrl.$setvalidity('fibonacci', false);
return undefined;
}
});
};
ngmodelcontroller是用来为ng-model提供了一组api。通过他我们可以他来确定ngmodel的 值是否是合法的。 我们这里只介绍其中和表单验证有关的几个方法和属性。
上面的例子中我们用到了$parsers这个属性和$setvalidity()这个方法。 $parsers里保存了一组function, 每当dom里数据变化的时候, 这组function会被一次调用。这里给了我们机会在用户修改了dom里值的时候, 去对新输入的值做校验。
“智能浮点(smart-float)”指令。它能把"1.2"或者"1,2"都转化为合法的浮点数"1.2"。注意,这里我们不能使用“数字输入类型”,因为html5的浏览器不允许用户输入像"1,2"这样的非法值。
html

<input type="text" ng-model="length" name="length" smart-float />
{{length}}<br />
<span ng-show="form.length.$error.float">this is not a valid float number!</span>
js

var float_regexp = /^\-?\d+((\.|\,)\d+)?$/;
app.directive('smartfloat', function() {
if (float_regexp.test(viewvalue)) {
ctrl.$setvalidity('float', true);
return parsefloat(viewvalue.replace(',', '.'));
ctrl.$setvalidity('float', false);