使用Angular,我正在尝试创建一个指令,该指令将放置在将启动搜索对话框的按钮上。搜索按钮有多个实例,但显然我只想要一个对话实例。该对话框应该从模板URL构建并拥有它自己的控制器,但是当用户选择一个项目时,该指令将用于设置该值。
有关如何使用指令创建对话框的任何想法吗?
这是我到目前为止所做的事情(基本上只是指令)......
http://plnkr.co/edit/W9CHO7pfIo9d7KDe3wH6?p=preview
以下是来自plkr的html ...
<a href="" my-find="setPerson">Find</a>
以下是plkr的代码......
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
var person = {};
person.name = 'World';
$scope.person = person;
$scope.setPerson = function(newPerson) {
person = newPerson;
$scope.person = person;
}
});
app.directive('myFind', function () {
var $dlg; // holds the reference to the dialog. Only 1 per app.
return {
restrict: 'A',
link: function (scope, el, attrs) {
if (!$dlg) {
//todo: create the dialog from a template.
$dlg = true;
}
el.bind('click', function () {
//todo: use the dialog box to search.
// This is just test data to show what I'm trying to accomplish.
alert('Find Person');
var foundPerson = {};
foundPerson.name = 'Brian';
scope.$apply(function () {
scope[attrs.myFind](foundPerson);
});
});
}
}
})
据我所知。我无法弄清楚如何使用指令内的模板创建对话框,因此它只出现一次,然后为其分配一个控制器。我想我可以在模板中分配控制器,但首先我需要弄清楚如何加载模板并调用我们的自定义jQuery插件来生成对话框(我们有自己的外观和感觉对话框)。
所以我相信问题是,如何在指令中加载模板?但是,如果有不同的思考方式,我也会对此感兴趣。
答案 0 :(得分:1)
我将使用bootstrap-ui向您展示如何使用它。 (如果不符合您的需要,您可以轻松修改它。)
这是模板的骨架。您通常可以绑定到指令范围内的任何属性和函数:
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
... // e.g. <div class="button" ng-click=cancel()></div>
</div>
<div class="modal-body">
...
</div>
<div class="modal-footer">
...
</div>
</div>
</div>
以下是如何在模块中创建/声明指令:
.directive("searchDialog", function ($modal) {
return {
controller: SearchDialogCtrl,
scope : {
searchDialog: '=' // here you will set two-way data bind with a property from the parent scope
},
link: function (scope, element, attrs) {
element.on("click", function (event) { // when button is clicked we show the dialog
scope.modalInstance = $modal.open({
templateUrl: 'views/search.dialog.tpl.html',
scope: scope // this will pass the isoleted scope of search-dialog to the angular-ui modal
});
scope.$apply();
});
}
}
});
然后控制器看起来像那样:
function SearchDialogCtrl(dep1, dep2) {
$scope.cancel = function() {
$scope.modalInstance.close(); // the same instance that was created in element.on('click',...)
}
// you can call it from the template: search.dialog.tpl.html
$scope.someFunction = function () { ... }
// it can bind to it in the search.dialog.tpl.html
$scope.someProperty;
...
// this will be two-way bound with some property from the parent field (look below)
// if you want to perform some action on it just use $scope.$watch
$scope.searchDialog;
}
然后你的标记你可以像这样使用它:
<div class="buttonClass" search-dialog="myFieldFromScope">search</div>
答案 1 :(得分:0)
我推荐这个插件:
https://github.com/trees4/ng-modal
在这里演示: https://trees4.github.io/ngModal/demo.html
以声明方式创建对话框;它适用于现有的控制器。可以根据需要设置对话框的内容样式。