2

我正在創建一個小應用程序,並且該模板具有以下指令。使用替換時,模板中不可見的角度隔離範圍值

smallgrid.directive.js:

angular.module('myActions') 
    .directive('smallgrid', ['$rootScope', function($rootScope) { 
     return { 
      restrict: "E", 
      scope: { 
       actionable: "=" 
      }, 
      controller: function($scope) { 
       $scope.setLocation = function() { 
        console.log("yee"); 
       }; 
      } 
     }; 
    }]) 
    .directive('three', function() { 
     return { 
      replace: true, 
      templateUrl: '/app/my_actions/directives/templates/grid3x3.template.html' 
     }; 
    }) 
    .directive('four', function() { 
     return { 
      replace: true, 
      templateUrl: '/app/my_actions/directives/templates/grid4x4.template.html' 
     }; 
    }) 
    .directive('five', function() { 
     return { 
      replace: true, 
      templateUrl: '/app/my_actions/directives/templates/grid5x5.template.html' 
     }; 
    }); 

grid3x3.template.html

<div class="k-edit-field" id="board"> 
    <div class="row" ng-click="setLocation()"> 
     {{actionable.probability}} 
    </div> 
</div> 

我使用這個指令如下:

<smallgrid three actionable="currentAction.actionable" ng-if="somecondition"></smallgrid> 

的UI呈現正常。但是,它顯示{{actionable.probability}}是空的,並且Click事件未觸發。但是,如果我刪除隔離的作用域並直接訪問該變量,則值可用。我知道當我使用隔離示波器時,在three指令中,我無法訪問smallgrid的值。有沒有辦法將smallgrid中的值傳遞給模板?

回答

1

將一個指令作爲指令的一個屬性傳遞,你肯定會遇到範圍問題。

如果對ng-transclude的嵌套指令使用範圍繼承,它會更好看。

所以,你的出發點應該是

<smallgrid actionable="currentAction.actionable" ng-if="somecondition"> 
    <three></three> 
</smallgrid> 

這樣<three>可以訪問$parent

function smallgrid() { 
 
    return { 
 
    restrict: "E", 
 
    transclude: true, 
 
    scope: { 
 
     actionable: "=" 
 
    }, 
 
    template: `<div ng-transclude></div>`, 
 
    controller: function($scope) { 
 
     $scope.setLocation = function() { 
 
     console.log("yee"); 
 
     }; 
 
    } 
 
    }; 
 
} 
 
function three() { 
 
    return { 
 
    template: `<div class="k-edit-field" id="board"> 
 
       <div class="row" ng-click="$parent.setLocation()"> 
 
        test = {{$parent.actionable.probability}} 
 
       </div> 
 
       </div>` 
 
    }; 
 
} 
 
function myController($scope) { 
 
    $scope.currentAction = {actionable: {probability: "test"}}; 
 
    $scope.somecondition = true; 
 
} 
 
angular.module('myApp', []); 
 
angular 
 
    .module('myApp') 
 
    .controller('myController', myController) 
 
    .directive('smallgrid', smallgrid) 
 
    .directive('three', three);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script> 
 
<div ng-app="myApp"> 
 
    <div ng-controller="myController"> 
 
    <smallgrid actionable="currentAction.actionable" ng-if="somecondition"> 
 
     <three></three> 
 
    </smallgrid> 
 
    </div> 
 
</div>

+0

真棒。感謝您的描述性答案。 –