在此plunk中,我有以下内容:
由于某种原因,打开模态时控件对象为空(查看控制台日志)。如何从控制器调用方法来设置字段值?
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>
的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;
});
答案 0 :(得分:3)
在打开模态和运行模态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();
});
};
$ uibModal.open()函数返回以下内容:
Object {result: Promise, opened: Promise, rendered: Promise}
在rendered
的promise块中,您可以安全地使用指令更改的字段。