angular的指令问题


我想写一个类似angularUI的tabset directive,看了一下源码,不是很明白。

HTML结构如下:


 html


 <tabset a="" b="" c="">
    <tab>
    </tab>
</tabset>

JS代码:


 javascript


 angular.module('angularTabset',[])
.directive('tabset',function(){
    return {
        restrict:'EA',
        replace: true,
        transclude: true,
        templateUrl: 'tabset.html',
        scope:{
            a:'=?',
            b:'=?',
            c:'=?'
        },
        controller:function($scope){
            this.a = $scope.a;
            this.b = $scope.b;
            this.c = $scope.c;
        },
        link: function (scope, iElement, iAttrs) {

        }
    }
})
.directive('tab', function () {
    return {
        restrict: 'EA',
        replace: true,
        require:'^tabset',
        transclude: true,
        templateUrl: 'tab.html',
        controller: function($scope){
            //How to get a,b,c here?
        },
        link: function (scope, iElement, iAttrs,ctrl) {

        }
    };
})

问题:

tab.html模板里用到了tabsetController里的a、b、c属性的值,我想在tabController里访问这三个值并实现双向绑定,该如何写?我试过在link函数里写,但貌似只执行一次,没有实现双向绑定。

angularjs JavaScript

这货不是灰加 11 years, 2 months ago
俺也不知道 answered 11 years, 2 months ago

这里有两个难点
1 子指令tab 需要使用require:'^tabset', 父指令
然后在link 函数 就可以使用第四个参数ctrl 这个就是父指令的控制器

link: function (scope, iElement, iAttrs, ctrl) {

}

2 传值 一般还是通过标签传值 声明式比较好



建议看一下官方的文档 说的比较清楚 Creating Directives that Communicate
https://docs.angularjs.org/guide/directive

Amulet answered 11 years, 2 months ago

Your Answer