AngularJS 指令中的require

  require参数可以被设置为字符串或数组,字符串代表另外一个指令的名字。require会将控制器注入到其值所指定的指令中,并作为当前指令的链接函数的第四个参数
字符串或数组元素的值是会在当前指令的作用域中使用的指令名称。指令得require参数的值可以用下面的前缀进行修饰,这会改变查找控制器时的行为:

?     在当前指令中没有找到所需要的控制器,会将null作为传给link函数的第四个参数。

^     指令会在上游的指令链中查找require参数所指定的控制器

?^    将前面两个选项的行为组合起来,选择地加载需要的指令并在父指令链中进行查找

没有前缀   指令将会在自身所提供的控制器中进行查找,如果没有找到任何控制器(或具有指定名字的指令)就抛出一个错误

  例子:

angular.module('myApp',[])  
    //定义第一个指令 bookList  
    .directive('bookList',function(){  
        return {  
            restrict:'ECAM',  
            controller:function($scope){  
                $scope.books=[  
                    {name:'php'},{name:'javascript'},{name:'java'}  
                ];  
                this.addBook=function(){  
                    $scope.$apply(function(){  
                        $scope.books.push({name:'Angularjs'});  
                    });  
                }  
            },  
            controllerAs:'bookListController',  
            //这个template中使用了第二个指令bookAdd  
            template:'<div><ul><li ng-repeat="book in books">{{ book.name }}</li></ul> <book-add></book-add> </div>',  
            replace:true  
        }  
    })  
    //定义第二个指令 bookAdd  
    .directive('bookAdd',function(){  
        return{  
            restrict:'ECAM',  
            require:'^bookList',  //这是个指令名
            template:'<button type="button">添加</button>',  
            replace:true,  
            link:function(scope,iElement,iAttrs,bookListController){  //这里引用了bookList指令的控制器  
                iElement.on('click',bookListController.addBook);  
            }  
        }  
    })  
    .controller('firstController',['$scope',function($scope){  
    }])  
原文地址:https://www.cnblogs.com/shawnhu/p/8540808.html