AngularJS Modal(ui.bootstrap.modal)在模态打开后无法触发jQuery事件(modalInstance.opened)

时间:2014-10-30 20:05:26

标签: angularjs angularjs-bootstrap

我正在使用AngularUI Bootstrap模式对话框(下面的示例)。打开模板后,我想触发一些jQuery事件。我正在使用modalInstance.opened方法,但获取空对象。

mycontroller.js

var app = angular.module('ui.bootstrap.demo');
 app.controller('ModalDemoCtrl', function ($scope, $modal, $log) {

  $scope.items = ['item1', 'item2', 'item3'];
  $scope.open = function (size) {

    var modalInstance = $modal.open({
     templateUrl: 'mytemplate.html',
     controller: 'ModalInstanceCtrl',
     size: size,
     resolve: {
        items: function () {
          return $scope.items;
        }
    }
   });

   modalInstance.result.then(function (selectedItem) {
    // form submit. Works fine.
   });

   modalInstance.opened.then(function (selectedItem) {
    // I want to trigger jQuery event on form element
    // When I try to access $("form") I am getting empty object
   });
 }
});

app.controller('ModalInstanceCtrl', function ($scope, $modalInstance, items) {
   $scope.form = {
     name : "Default Name"
     myItem : items[0]
   }
   $scope.ok = function () {
     $modalInstance.close($scope.form);
   };
});

mytemplate.html

<form>
  <label>Name</label>
  <input type="text" name="name" ng-bind="form.name" />
  ...
</form>

2 个答案:

答案 0 :(得分:2)

我认为,由于模态内容被转换,开放事件会触发,但还没有使dtml可用。

0的简单超时会将其移至事件后面。

   $timeout ( function(){
        console.log(angular.element("form"));
    },0);

<强> fiddle

答案 1 :(得分:1)

您可以创建自定义指令emit-event-when-loaded并将其附加到表单

示例:

app.controller('ModalInstanceCtrl', function ($scope, $modalInstance, items) {
    $scope.form = {
        name: "Default Name",
        myItem: items[0]
    }
    $scope.ok = function () {
        $modalInstance.close($scope.form);
    };
}).directive("emitEventWhenLoaded", function() {
    return function() {
        console.log($("form")); // $("form") is defined
        angular.element("form").trigger("custom-event"); // do whatever you want
    }
});

然后在HTML中:

<form emit-event-when-loaded>
<label>Name</label>
<input type="text" name="name" ng-bind="form.name" />

更新了小提琴:http://jsfiddle.net/vugncsbt/3/