如何在转换后访问控制器范围?

时间:2013-09-06 17:03:52

标签: angularjs angularjs-directive angularjs-scope transclusion

如果我错了,请纠正我,但我认为在firstDirective场景中,我无法实现secondDirective的行为,因为它正在创建一个兄弟范围;我无法访问模板的控制器范围。我希望secondDirective的行为具有翻译的力量。有没有办法实现这个目标?或者我是以错误的方式攻击这个问题?

http://jsfiddle.net/3QRDt/68/

var app = angular.module('myApp', []);

app.directive('firstDirective', function(){
    return {
        restrict: 'EA',
        replace: true,
        scope: true,
        transclude: true,
        template: '<div id="holder" data-ng-controller="MyController">{{shouldBeOpen}}<div ng-transclude></div><button data-ng-click="close()">Close</button></div>',
        link: function(scope, element) {
            scope.openDirective = function() {
                scope.open()
                alert("Hello from Directive")
            }
            scope.hello ='dad'            
        }
    };
})
.directive('secondDirective', function(){
    return {
        restrict: 'EA',
        replace: true,
        scope: true,
        transclude: true,
        template: '<div id="holder" data-ng-controller="MyController">{{shouldBeOpen}}<button data-ng-click="openDirective()">{{hello}} Open</button><button data-ng-click="close()">Close</button></div>',
        link: function(scope, element) {
            scope.openDirective = function() {
                scope.open()
                alert("Hello from Directive")
            }
            scope.hello ='dad'            

        }
    };
});;

app.controller('MyController', ['$scope', function($scope) {
    $scope.shouldBeOpen = false
    $scope.close = function() {
        $scope.shouldBeOpen = false
    }
    $scope.open = function() {
        $scope.shouldBeOpen = true
        alert("Hello from Controller")
    }
}]);

1 个答案:

答案 0 :(得分:0)

您可以使用$$prevSibling从transcluded范围引用指令创建的隔离范围:

<button data-ng-click="$$prevSibling.openDirective()">{{hello}} Open</button>