2016-03-14 50 views
0

我有一個指令,有一個transclude。 transcluded內容是一個表單,它具有調用(父級)控制器中的方法的提交選項。這個方法是從transcluded範圍調用的,所以我在控制器中訪問的任何變量都可以通過this.variable訪問,因爲這反映了調用者(當前)範圍。但是,$scope.variable未定義,因爲$scope是父範圍的範圍,它是控制器的範圍。

我確實應該使用this來訪問窗體值,還是有一個約定,我應該通過(父)控制器中的$scope來實現?

聲明:我知道我沒有使用controllerAs功能,現在我無法更改該項目。

Plunker證明問題: http://plnkr.co/edit/TdgZFIRNbUcHNfe3a7uO?p=preview

正如你所看到的指令更新裏面的值,當你在文本框中更改值。這與預期的一樣,都涉及到transcluded範圍。指令外部的{{name}}不會更改,因爲這是父範圍而不是轉義範圍。單向行駛。

什麼是合適的解決方案?使用this.name或修改指令,以便$scope.name可以在指令外使用?

對於那些誰喜歡過plunkers代碼:

HTML:

<body ng-app="docsTransclusionExample"> 
    <div ng-controller="Controller"> 
    {{name}} 
    <my-dialog> 
     Check out the contents, {{name}}! 
     <form> 
     <input ng-model="name"> 
     </form> 
    </my-dialog> 
    </div> 
</body> 

指令:

(function(angular) { 
    'use strict'; 
angular.module('docsTransclusionExample', []) 
    .controller('Controller', function($scope) { 
    $scope.name = 'Tobias'; 
    }) 
    .directive('myDialog', function() { 
    return { 
     restrict: 'E', 
     transclude: true, 
     scope: {}, 
     templateUrl: 'my-dialog.html' 
    }; 
    }); 
})(window.angular); 

指令模板:

<div class="alert" ng-transclude></div> 

回答

1

這是有關「的點規則「在angu LAR。

這意味着,當你有範圍heirarchy,並且子範圍試圖修改父範圍時,它創建它自己的範圍。

當您使用的數據對象,您可以訪問成員「以一個點」,所以你不;噸直接改變的範圍,而不是創建一個新的子範圍

在你的情況

$scope.name = 'Tobias'; 

shuold改變

$scope.data = {name: 'Tobias'}; 

見plunker: http://plnkr.co/edit/RqORVm8r4jph532dT6nY?p=preview

進一步閱讀:

Why don't the AngularJS docs use a dot in the model directive?

https://www.youtube.com/watch?v=DTx23w4z6Kc

PS。

  1. 這不涉及指令transclusion(關於構建DOM)。
  2. 如果你這樣做:scope: {} in directive,你明確地創建了一個子範圍。
+0

感謝您的完整答案,包括閱讀材料。很簡單的修復。 – bastijn

相關問題