范围没有达到我对复合指令的期望

时间:2013-12-23 15:23:03

标签: javascript angularjs

我已经设置了一个JS小提琴here,它显示了一个指令由其他指令组成的情况。在这种情况下,范围对象没有达到我的预期。

第一个控件由html组成,因此有一个面板,该面板内部是一个控件,控件内部是一个通过ng-click绑定到“hi()”的按钮。此方案工作正常,因为创建了一个转换范围。

在第二个示例中,实现了相同的视觉效果,但不是指定面板明确性,而是在控件模板中声明它。转换的范围在这里变得非常奇怪,导致ng-click不会触发。

我可以通过绑定到'$ parent。$ parent。$ parent.hi()'来触发事件。我希望范围在两种情况下都能以相同的方式执行,因为(在我看来)它实际上是相同的。我弄错了吗?

使用Javascript:

angular
.module('demo', [])
.controller('MainController', function($scope) {
    $scope.hi = function() {
       alert('Button click was fired!');
    };
})
.directive('panel', function() {
    return {
        transclude: true,
        scope: {
            title: '@'
        },
        template: '<div class="panel"><h4>{{title}}</h4><div ng-transclude></div></div>'
    };
})
.directive('control', function() {
    return {
        transclude: true,
        scope: {
            label: '@'
        },
        template: '<div class="control"><h4>{{label}}</h4><div ng-transclude></div></div>'
    };
})
.directive('compositeControl', function() {
    return {
        transclude: true,
        scope: {
            label: '@'
        },
        template: '<div panel title="Panel with embedded control"><div class="control"><h4>{{label}}</h4><div ng-transclude></div></div></div>'
    };
});

HTML:

<div ng-app="demo">

<div ng-controller="MainController">
    <h4>Button outside of transcluded scope</h4>
    <button ng-click="hi()">Button Outside</button>

    <h4>Working</h4>        
    <div panel title="Panel Title">
        <div control label="My Control Label">
            <button ng-click="hi()">Button Inside</button>
        </div>
    </div>        

    <h4>Broken</h4>        
    <div composite-control label="My Composite Control Label">
        <button ng-click="hi()">Button Inside</button>
    </div>      

    <h4>Working, but not really</h4>        
    <div composite-control label="My Composite Control Label">
        <button ng-click="$parent.$parent.$parent.hi()">Button Inside</button>
    </div>
</div>    

0 个答案:

没有答案
相关问题