Angular UI模态控制器不会暴露给指令

时间:2014-06-09 15:45:01

标签: javascript angularjs angular-ui

我需要创建一个可以在Angular UI模式中使用的指令。该指令还需要了解模态控制器,以便使用它的某些功能。我现在拥有的:

JS:

'use strict';

var DemoApp = angular.module('DemoApp', [ 'ui.bootstrap' ]);

DemoApp.controller('PageController', ['$scope', '$modal', function($scope, $modal){
  $scope.openModal = function(){
    var scope = $scope.$new(true);

    $modal.open({
      'templateUrl' : 'modal.html',
      'controller' : 'ModalController',
      'scope' : scope
    });
  }
}]);

DemoApp.controller('ModalController', ['$scope', '$modalInstance', function($scope, $modalInstance){
  $scope.ok = function() {
    $modalInstance.dismiss();
  };

  $scope.cancel = function() {
    $modalInstance.dismiss();
  };
}]);

DemoApp.directive('expression', function() {
  return {
    restrict : 'A',
    require : ['ngModel', '^ModalController'],
    link : function(scope, element, attrs, controllers) {
      console.log(arguments);
    }
  };
});

模态模板:

<div class="modal-header">
  <h3>Test!</h3>
</div>
<div class="modal-body">
  <input data-ng-model="someValue" expression>{{someValue}}
</div>
<div class="modal-footer">
  <button class="btn btn-primary" data-ng-click="ok()">Ok</button>
  <button class="btn btn-warning" data-ng-click="cancel()">Cancel</button>
</div>

红色按钮:

<button id="demoButton" class="btn btn-primary" data-ng-click="openModal()">Click me!</button>

但是当创建模态时ModalController未解决,我收到$compile:ctreq错误:

Error: [$compile:ctreq] http://errors.angularjs.org/1.2.17/$compile/ctreq?p0=ModalController&p1=expression
    at Error (native)
    at http://ajax.googleapis.com/ajax/libs/angularjs/1.2.17/angular.min.js:6:450
    at D (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.17/angular.min.js:51:80)
    at http://ajax.googleapis.com/ajax/libs/angularjs/1.2.17/angular.min.js:51:137
    at Array.forEach (native)
    at q (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.17/angular.min.js:7:280)
    at D (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.17/angular.min.js:51:114)
    at N (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.17/angular.min.js:54:128)
    at g (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.17/angular.min.js:47:82)
    at g (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.17/angular.min.js:47:99) <input data-ng-model="someValue" expression="" class="ng-pristine ng-valid">

我尝试调试代码:getControllers()某处6433左右LOC位于angular.js用于搜索控制器:value = value || $element[retrievalMethod]('$' + require + 'Controller');,所以我尝试要求Modal代替{ {1}}(ModalController附加了Angular),但它没有帮助。我无法理解Controller是如何工作的(进入它,但它是低级别的)。所以,我感到困惑并感激任何帮助。

我已创建了Plunk,因此您可以在控制台中播放并查看我的意思。

1 个答案:

答案 0 :(得分:3)

请结帐更新plunker

  1. ModalController范围不是PageController的子范围,因此如果您需要将变量传递给ModalController,则应通过直接解析依赖关系来实现。

  2. 在您的指令中,您可以将范围设置为ModalController范围的子级,这样您就可以访问其中定义的函数,而不需要ModalController