ps0*_*604 5 angularjs angular-ui angular-ui-bootstrap angular-directive
这个插件的目的是将元素从控制器转换为Angular UI Modal,其中Modal由指令包装.解决方案应遵循以下前提:
input1在控制器中声明了一个应该在Modal中设置值的变量).content元素来转换字段.此元素位于模态的模板中.我不确定这个模板何时可以转录它.总而言之,目标是在控制器HTML标记中声明一组字段并在模态中可用,其中模式包含在指令中,范围在控制器中管理.任何想法将不胜感激.
HTML
<div the-modal control="modalCtl">
<p>some text</p>
<input type="text" ng-model="input1" />
</div>
<button type="button" ng-click="open()">Open me!</button>
Run Code Online (Sandbox Code Playgroud)
使用Javascript
var app = angular.module("app", ['ui.bootstrap']);
app.controller("ctl", function($scope,$timeout) {
$scope.modalCtl = {};
$scope.input1 = "abc";
$scope.open = function(){
$scope.modalCtl.openModal();
};
});
app.directive("theModal", function($uibModal) {
return {
restrict: "AE",
scope: {
control: "="
},
transclude: true,
link: function (scope, element, attrs, ctrl, transclude) {
scope.control = scope.control || {}
scope.control.openModal = function () {
scope.instance = $uibModal.open({
animation: false,
scope: scope,
template: '<div>in the template</div><div class="content"></div>'
});
element.find('.content').append(transclude());
};
}
}
});
Run Code Online (Sandbox Code Playgroud)
你已经足够接近实现你的目标,但是,你需要考虑以下几点:
首先,根据UI Bootstrap文档,默认情况下该方法中有一个appendTo属性.options$uibModal.open()body
如果
appendTo未指定,则模式将附加到body您的页面并成为该页面的直接子项body.因此,.content在您的指令中查询element.find('.content')将不起作用,因为它不存在.
其次,AngularJS附带jQLite,jQuery的轻量级版本.这意味着对jQuery的大多数功能的支持有限.一种这样的情况是该.find()方法仅适用于标签名称.
为了使它与jQuery一起工作(虽然你真的不必因为你仍然可以.children()在链中使用来查询嵌套的DOM元素),你必须在Angular之前加载jQuery(我想你已经有了) .
有关angular.element详细信息,请参阅AngularJS文档.
渲染DOM需要花费一点时间用于Angular,因为它需要制作与范围和视图相关的正确绑定,以完成摘要周期,等等.因此,您最终可能会立即查询实际上可能尚未呈现的DOM元素.
等待DOM呈现和完成摘要周期的技巧是将与DOM相关的代码
$timeout包装成包装器.
考虑到以上几点,openModal自定义指令的link函数中的方法theModal应如下所示:
scope.control.openModal = function () {
scope.instance = $uibModal.open({
animation: false,
scope: scope,
template: '<div>in the template</div><div class="content"></div>',
/**
* Make sure the modal is appended to your directive and NOT `body`
*/
appendTo: element
});
/**
* Give Angular some time to render your DOM
*/
$timeout(function (){
/**
* In case jQuery is not available
*/
// var content = element.children('.modal').children('.modal-dialog').children('.modal-content').children('.content');
/**
* Since you have jQuery loaded already
*/
var content = element.find('.content');
/**
* Finally, append the transcluded element to the correct position,
* while also making sure that the cloned DOM is bound to the parent scope (i.e. ctl)
*/
transclude(scope.$parent, function(clonedContent){
content.append(clonedContent);
});
});
};
Run Code Online (Sandbox Code Playgroud)
请注意该transclude函数如何控制您如何将某些已转换的DOM绑定到自定义作用域而不是默认指令的作用域.普通transclude()调用将考虑当前可用的范围对象 - 即指令的范围 - 用于绑定已转换的DOM.
| 归档时间: |
|
| 查看次数: |
2016 次 |
| 最近记录: |