2017-02-16 57 views
0

我有一個帶有確認和取消方法的父指令模式指令。如何從子指令中調用AngularJS父指令作用域方法

 ngDialog.open({ 
      scope  : true, 
      showClose : false, 
      template : theTemplate, 
      className : 'ngdialog-theme-prompt -small', 

      controller : ['$scope', function Ctrl($scope) { 
       $scope.message = message; 

       $scope.confirm = function(){ 
        $scope.closeThisDialog(); 
        resolve(true); 
       }; 

       $scope.cancel = function(){ 
        $scope.closeThisDialog(); 
        resolve(false); 
       }; 
      }] 

     }).closePromise.then(function() { 
      resolve(false); 
     }) 

模板是另一個指令。

<form class="edit-stakes-content"> 
    <ul> 
     <li ng-repeat="stake in settings track by $index"> 
      <input type="number" name="input" pattern="^\d+$" min="0" value="{{stake}}" /> 
     </li> 
    </ul> 
    <div class="edit-stakes-control"> 
     <button ng-click="cancel();" class="apl-btn apl-btn-link apl-btn-large" translate>CANCEL</button> 
     <button ng-click="confirm();" autofocus="true" class="apl-btn apl-btn-update apl-btn-large" translate>SAVE</button> 
    </div> 
</form> 

在我希望能夠進行一些驗證和POST到服務器,然後調用父模態指令,確認或取消方法,模態的子指令。

與此類似:

Directive.$inject = ['UserSettings']; 

function Directive(UserSettings) { 
    function Link($scope) { 

     $scope.settings = angular.copy(UserSettings.get('presetStakeSettings').settings); 

     $scope.cancel = $scope.$parent.cancel(); 

    } 

    return { 
     'link': Link, 
     'restrict': 'E', 
     'replace': true, 
     'templateUrl': 'betting/edit-stakes/edit-stakes.html' 
    } 
} 

調用父類的方法拋出一個JavaScript錯誤出現在$範圍$ parent.cancel不是函數又似乎做的工作。

有沒有更好的方式來實現孩子到家長溝通沒有JavaScript錯誤?

回答

0

$scope.$parent一般可以認爲是反模式,它幾乎沒有什麼好用處,通常表示指令設計存在問題或者範圍繼承問題還不是很好理解。

Directive指令不要求新的作用域,因此可以認爲它與模態控制器中作用域的作用域是一樣的。這意味着$scope.$parent引用了不具有cancel屬性的模式範圍(可能爲根範圍)的父項。

這也意味着$scope.settings賦值影響控制器範圍 - 雖然它顯然不應該。在此指令中繼承範圍scope: true會更好。

無論是否有scope: true也沒關係,但$scope.cancel將在指令中可用。它從模態範圍繼承。沒有理由去做

$scope.cancel = $scope.$parent.cancel(); 
相關問題