【问题标题】:Get directions childs tags AngularJS获取方向子标签AngularJS
【发布时间】:2016-04-20 13:25:36
【问题描述】:

我做了这个指令,我在我的html中调用

<my-datepicker />

我现在想做的,就是把它消耗掉,这样我就可以做这样的事情了

<my-datepicker >
    <my-day>{{date}}</my-day>
    <my-month>{{moth}}</my-month>
    <my-year>{{year}}</my-year>
</my-datepicker>

导致my-datepicker指令可以获取子元素。

你怎么能做到这一点?您是否需要让孩子喜欢独立指令,如何在 parent(my-datepicker) 指令中从他们那里获取值

【问题讨论】:

    标签: angularjs angularjs-directive angularjs-scope


    【解决方案1】:

    你可以像这样访问父指令控制器:

    app.directive('myDay', function () {
        return {
            restrict: 'E',
            require: '^myDatepicker',
            link: function (scope, element, attrs, parentCtrl) {
                parentCtrl.doSomething();
            }
        };
    });
    

    在父母中:

    app.directive('myDatepicker', function () {
        return {
            restrict: 'E',
            controller: function () {
                this.doSomething = function () {
                    alert('Do something in parent');
                };
            }
        };
    });
    

    【讨论】:

    • 我想这就是我要找的。我会在尝试后报告。谢谢
    【解决方案2】:

    我认为扩展指令的最佳方法是将参数(日期月份 ec...)作为属性传递。

    你的html应该是这样的

    <my-datepicker day="day" month="month" year="year"/>
    

    在您的指令中,您应该能够通过在作用域中声明这些变量来检索它们。

    function myDatepicker() {
    var directive = {
        templateUrl: 'yourtemplate.html',
        restrict: 'E',
        link: link,
        scope: {
            date: '=',
            month: '=',
            year: '='
        }
    }
    
    return directive;
    
    function link(scope, element, attrs) {
        // use here scope.date scope.month and scope.year
    }
    

    };

    【讨论】:

    • 感谢您的回答。我明白你为什么这么认为。但我想这样做的原因是因为我要对这些标签进行一些 html 渲染和样式
    猜你喜欢
    • 1970-01-01
    • 2015-06-24
    • 1970-01-01
    • 2015-12-27
    • 1970-01-01
    • 2017-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多