2014-10-30 30 views
2

我正在使用AngularUI Bootstrap模式對話框(下面的示例)。一旦模板打開,我想觸發一些jQuery事件。我正在使用modalInstance.opened方法,但獲取空對象。AngularJS Modal(ui.bootstrap.modal)打開模式後無法觸發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> 
+0

的jsfiddle興趣的人:http://jsfiddle.net/vugncsbt/1/ +1這是一個很好的問題。但是,如果我們知道您在做什麼,也許我們可以建議一種解決方法?你需要表單來從jQuery中激發一個自定義事件嗎? – soktinpk 2014-10-30 20:44:15

+0

我必須做一個像$(「#myForm」)。validate(validationConfig)'這樣的jQuery表單驗證。由於我的應用程序的驗證已經寫入jQuery中,我必然會使用jQuery驗證而不是angularJS驗證 – user2300875 2014-10-30 20:56:26

回答

2

我想既然模態內容transcluded打開事件觸發,但還沒有做出HTML提供給DOM。

0的簡單超時會將其移到事件後面。

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

fiddle

+0

我正在使用此解決方案。正如soktinpk提到的有關添加自定義指令'emit-event-when-loaded'時的情況,但我想知道如果我們無法實現它在文檔中所說的話,那麼modalInstance.opened方法的用法是什麼。 **打開 - 在下載內容模板並解析所有變量後打開模式時解決的承諾** – user2300875 2014-10-30 21:21:53

+0

@ user2300875 *下載*,不必呈現內容。它不違反它的合同。必須解析變量並且內容必須準備好,但不一定附加到DOM。 – soktinpk 2014-10-30 22:22:18

+0

這工作,但記得添加$超時作爲依賴項 – mintedsky 2015-12-14 18:59:05

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/