首页 > 解决方案 > 无法访问角度指令的隔离范围

问题描述

第一指令:

app.directive("myDirectiveOne", function($rootScope){
    return {
        templateUrl : "/custom-one-html.html",
        restrict: "AE", 
        replace:true,
        scope: {
            somedata: "=",
            flags: "=",
            functionone: "&"
        }
        ,controller: function($rootScope,$scope, $element) {
           $scope.firstFunction = function(){
                console.log("First function is getting called")
           }
$scope.$on('firstBroadcast',function(event, data){
                $rootScope.$broadcast('secondBroadcast', data)
            });

    }

第二条指令:

app.directive("myDirectiveTwo", function($rootScope){
    return {
        templateUrl : "/custom-two-html.html",
        restrict: "AE", 
        replace:true,
        scope: {
            data: "=",
            functiontwo: "&"
        }
        ,controller: function($rootScope,$scope, $element) {
           $scope.secondFunction = function(){
                console.log("Second function is getting called")
                $rootScope.$broadcast('firstBroadcast', {})
           }
$scope.$on('secondBroadcast',function(event, data){
                $scope.callSomeFunctionWithData(data);
            });
$scope.secondFunction();

    $scope.editFunction = function(x){
console.log("This is the edit function", x);
        }

父控制器:

$scope.parentFuntion = function(){
        console.log("No trouble in calling this function")
}

所以,问题是当我尝试从 html 模板调用函数时myDirectiveTwo,处于活动状态的控制器是父控制器,而不是孤立的控制器。

可能与我正在使用的广播有关吗?

html代码:

<div ng-repeat="x in data">
    <h5>{{x.name}}</h5>
    <button ng-click="editFunction(x)">Edit</button>
</div>

奇怪的是我得到了数据值并且 ng-repeat 在加载时工作正常。但是,当我单击按钮时,它什么也没做。如果我在父控制器中添加相同的功能,它会被调用.. :( 如何使隔离范围控制器再次活动..?

标签: angularjsangularjs-directiveangularjs-scopeangular-controllerangular-broadcast

解决方案


问题是 ng-repeat 创建了一个子范围,因此editFunction最终位于父范围内。

来自文档

...每个模板实例都有自己的范围,其中给定的循环变量设置为当前集合项...

文档在这里

您可以通过获取按钮元素的范围并检查 $parent 来验证这是问题所在,因此angular.element(document.getElementsByTagName("button")).scope()

尽管考虑了代码异味,但您可以将 $parent 附加到您的函数调用以访问它,但请记住,这现在对您的 HTML 结构产生了依赖性。

<button ng-click="$parent.editFunction(x)">Edit</button>


推荐阅读