【问题标题】:How do I access a controllers scope after a transclusion?嵌入后如何访问控制器范围?
【发布时间】:2013-09-10 20:37:07
【问题描述】:

如果我错了,请纠正我,但我认为在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")
    }
}]);

【问题讨论】:

    标签: angularjs angularjs-directive angularjs-scope transclusion


    【解决方案1】:

    您可以使用$$prevSibling 来从嵌入范围引用到由指令创建的隔离范围:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-03
      • 1970-01-01
      • 2018-08-30
      • 2014-04-21
      • 1970-01-01
      • 2016-03-28
      • 1970-01-01
      • 2014-07-02
      相关资源
      最近更新 更多