企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
深入理解自定义指令scope的绑定 首先在directive中,使用scope就相当于隔离了作用域,即父controller访问不到子controller的变量,子controller访问不到父controller的变量 ~~~ <body ng-app = "myApp"> <div ng-controller="fatherCtrl"> <input type="text" ng-model="bind"> <my-directive ></my-directive> </div> <script> angular.module('myApp',[]) .controller('fatherCtrl',function () { }) .directive('myDirective',function () { return { restrict:'AE', scope:{ }, template:' <div ng-click="click()">shenmegui</div>', link:function (scope) { scope.click=function () { console.log(scope.bind) } } } }) </script> ~~~ #### 如果使用了scope,隔离作用域,那子元素将访问不到父元素的属性, #### 要使子元素可以跟父元素的数据进行绑定,可以使用scope里面的三个符号 - @:单向绑定 - =:双向绑定 - &:用于绑定函数 所以要使上面的自作用域可以访问得到父作用域的元素,可以使用=号的方法, 使用注意,我们需要在html的自定义指令中加入 一个属性 例如: ~~~ <my-directive son-bind="bind"></my-directive> ~~~ **注:在js文件中的驼峰,在html中都要变为-加上小写** 然后在directive的js文件中的scope书写: ~~~ scope:{ sonBind:"=" }, ~~~ 然后我们directive js里的sonBind就相当于 父controller里的bind ~~~ .directive('myDirective',function () { return { restrict:'AE', scope:{ sonBind:"=" }, template:' <div ng-click="click()">shenmegui</div>', link:function (scope) { scope.click=function () { console.log(scope.sonBind) } } } }) ~~~ 如果使用的是单向绑定: ~~~ scope:{ sonBind:"@" }, ~~~ 那html里的bind要改为表达式的形式: ~~~ <my-directive son-bind="{{bind}}"></my-directive> ~~~ 然后这个&使用来绑定函数的,如: ~~~ <input type="text" ng-model="bind" ng-blur="Dosome()"> <my-directive son-bind="Dosome()"></my-directive> ~~~ js: ~~~ restrict:'AE', scope:{ sonBind:"&" }, template:' <div ng-click="sonBind()">shenmegui</div>' + ' <button ng-click="sonBind()">按钮</button>', ~~~ 这样,点击自定义指令的东西,就会跟父级controller触发一样的函数 * * * * * ### 使用了自定义指令,当父控制器作用域绑定了vm,如何获取父作用域的数据, - 当父作用域绑定了vm,而自定义指令没有隔离作用域时,可以在自定义指令的link,或controller里,写 scop.vm.xx获取父控制器的数据,注意不能写vm.xx获取scope.xx例如: ~~~ angular.module('myApp',[]) .controller('fatherCtrl',function ($scope) { var vm=this vm.name={ date:1, age:20 } }) .directive('myDirective',function () { return { restrict:'AE', template:' <div ng-repeat="x in sonBind">shenmegui</div>' + ' <button>按钮</button>', link:function (scope) { console.log(scope.vm.name) } } }) ~~~ 这样就能获取父控制器的数据 * * * * * 使用ng-transclued的时候, 自定义指令的transUrl里面的html最外层必须有一个标签把他包起来,否则,这个自定义指令不生效,如: ~~~ <div class="checkIn-header clearfix"> <p class="pull-right">累计签到天数<span class="week">{{data.maxSignNum}}</span>天</p> </div> <div id="checkIn-datepicker"> </div> <div class="checkIn-footer"> <button class="btn btn-checkIn">{{}}</button> <a>签到规则</a> </div> ~~~ 这样只是3个同级的div,并且3个同级的div没有父级,而自定义指令里的link无法操控3个div,所以不生效,所以换成下面这样: ~~~ <div> <div class="checkIn-header clearfix"> <p class="pull-right">累计签到天数<span class="week"> {{data.maxSignNum}}</span>天</p> </div> <div id="checkIn-datepicker"> </div> <div class="checkIn-footer"> <button class="btn btn-checkIn">{{}}</button> <a>签到规则</a> </div> </div> ~~~