编程语言
首页 > 编程语言> > javascript-Angular UI Modal控制器未暴露于指令

javascript-Angular UI Modal控制器未暴露于指令

作者:互联网

我需要创建一个可以在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">

我尝试调试代码:angular.js的6433 LOC附近的getControllers()用于搜索控制器:value = value || $element [retrievalMethod](‘$’require’Controller’);,所以我尝试使用Modal而不是ModalController(Controller由Angular附加),但这没有帮助.我无法理解$element [retrievalMethod]的工作原理(进入其中,但它是底层的).因此,我很困惑,感谢您的帮助.

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

解决方法:

请,结帐更新为plunker

> ModalController范围不是PageController的子范围,因此,如果需要将变量传递给ModalController,则应通过直接解决依赖关系来实现.
>在指令中,您可以将范围设置为ModalController范围的子级,因此您可以访问在那里定义的函数,而无需ModalController.

标签:angularjs,angular-ui,javascript
来源: https://codeday.me/bug/20191121/2053302.html