2014-03-18 64 views
0

說我有以下兩條指令,與工作相互AngularJS指令使用所需的控制器

directive('parent', function() { 
    return { 
     scope: {}, 
     require: 'ngModel', 
     controller: function($scope) { 
      this.doSomething = function() { 
       //How to use ngModelController here? 
      }; 
     }, 
     link: function(scope, element, attr, ngModelController) { 
     } 
    }; 
}); 

directive('child', function() { 
    return { 
     scope: {}, 
     require: '^parent', 
     link: function(scope, element, attr, parent) { 
      parent.doSomething(); 
     } 
    }; 
}); 

我如何使用ngModelControllerparent控制器內?我想我可以在鏈接函數裏面做scope.ngModelController = ngModelController,但是這看起來很亂。有更好的解決方案嗎?

+0

我想你可以把它放在鏈接功能的範圍?看起來有點不好意思,但想不到別的... – aet

+0

嘗試要求:'?ngModel'。這應該通過父母尋找控制器。 –

+0

顯然這是重複的! http://stackoverflow.com/questions/21231294/angularjs-inject-required-directive-controller-into-the-controller-instead-of-t – grivescorbett

回答

0

這是不是很哈克?

directive('parent', function() { 
    var ngModelCtrl = null; 
    return { 
     scope: {}, 
     require: 'ngModel', 
     controller: function($scope) { 
      this.doSomething = function() { 
       //How to use ngModelController here? 
       if (ngModelCtrl) { 
       } 
      }; 
     }, 
     link: function(scope, element, attr, ngModelController) { 
      ngModelCtrl = ngModelController; 
     } 
    }; 
});