在 Angular UI Modal 中集成指令

ps0*_*604 1 angularjs angularjs-directive

在这个plunk我有以下内容:

  • 在控制器和指令之间共享的控制对象。
  • 该指令在控制对象中声明了一个方法。
  • 控制器调用方法来设置一个值。
  • 该指令包含在 Angular UI Modal 中。

由于某种原因,打开模态时控制对象为空(查看控制台日志)。如何从控制器调用方法来设置字段值?

HTML

<div ng-app="app" ng-controller="myCtl">

        <button ng-click="openModal()">Open modal</button>

        <script type="text/ng-template" id="myModalContent.html">

            <div class="modal-header">
                <h4 class="modal-title">The Title</h4>
            </div>

            <ddl control="ddlControl"></ddl>                

            <div class="modal-footer">
                <button type="submit">Submit</button>
            </div>

       </script>

    </div>
Run Code Online (Sandbox Code Playgroud)

Javascript

var app = angular.module('app', ['ui.bootstrap']);
app.controller('myCtl', function($scope,$uibModal) {

        $scope.ddlControl = {};

        $scope.openModal = function() {
          $scope.modalInstance = $uibModal.open({
              templateUrl: 'myModalContent.html',
              scope: $scope
            }); 

          console.log($scope.ddlControl);
          $scope.ddlControl.set();

        };
})

.directive('ddl', function () {

    var directive = {};
    directive.restrict = 'EA';
    directive.scope = {
         control: '='
    };
    directive.template = '<div>someValue: {{someValue}}</div>';
    directive.link = function (scope, element, attrs) {

        scope.control = scope.control || {};

        scope.control.set = function() {
           scope.someValue = 1;
        };

    };
    return directive;
});
Run Code Online (Sandbox Code Playgroud)

com*_*ghz 5

在打开模态和运行模态 HTML 摘要之间存在竞争条件。

当按钮被点击时$scope.openModal()执行。模态打开并进入摘要阶段。但是javascript不会等到消化完成,所以它会继续执行$scope.openModal()直到结束。

您需要处理 $uibModal.open().rendered() 的承诺。uibModal 在rendered完成后解决承诺。

    $scope.openModal = function() {
      $scope.modalInstance = $uibModal.open({
          templateUrl: 'myModalContent.html',
          scope: $scope
        }).rendered.then(function() {
             console.log($scope.ddlControl);
             $scope.ddlControl.set(); 
        }); 
    };
Run Code Online (Sandbox Code Playgroud)

$uibModal.open() 函数返回以下内容:

Object {result: Promise, opened: Promise, rendered: Promise}

在 的 promise 块中rendered,您可以安全地使用已被指令更改的字段。

Plunker:http ://plnkr.co/edit/GnIThstxkuR06felh8Pe?p=preview