I am working on my first Angular app (yay!). I'm trying to have a generic modal component which can declare a title, custom content and any number action buttons. Background setup follows, then my questions at the bottom.
Here's how I'd like to use the directive.
<!-- in app/views/library/index.html -->
<!-- outside <modal> #i_work works great -->
<select id="i_work">
<option value="{{libraryType.id}}" ng-repeat="libraryType in libraryTypes">{{libraryType.name}}</option>
</select>
<modal id="library_new" title="My Custom Title">
<form>
<!-- inside <modal> #i_dont_work doesn't work -->
<select id="i_dont_work">
<option value="{{libraryType.id}}" ng-repeat="libraryType in libraryTypes">{{libraryType.name}}</option>
</select>
</form>
<modal-buttons>
<!-- [toggle-modal] is another directive that shows/hides a given <modal> -->
<button type="button" toggle-modal="library_new">cancel</button>
<button type="submit" ng-click="addLibrary()">save</button>
</modal-buttons>
</modal>
Here's the directive code:
// in app/scripts/directives/modal.js
'use strict';
angular.module('sampleAngularApp')
.directive('modal', [function () {
return {
templateUrl: '/scripts/directives/modal.html',
restrict: 'E',
transclude: true,
link: {
pre: function preLink(scope, element, attrs) {
scope.id = attrs.id;
scope.title = attrs.title;
},
post: function preLink(scope, element, attrs) {
// hacky-hack to transclude specific content into other targets.
// bound event handlers should be preserved (as implemented they are).
// this actually works
var buttonWrap = element.find('modal-buttons');
buttonWrap.children().each(function (index, button) {
element.find('.modal-footer').append(button);
});
buttonWrap.remove();
}
}
};
}]);
... and the directive template:
<!-- in app/scripts/directives/modal.html -->
<div class="modal" role="dialog">
<div class="modal-header">
<span class="title">{{title}}</span>
<button type="button" class="close" toggle-modal="{{id}}">close</button>
</div>
<!-- the contents of .modal-body should be everything inside <modal> above, -->
<!-- except for <modal-buttons> -->
<div class="modal-body" ng-transclude />
<!-- the contents of .modal-footer should be the contents of <modal-buttons> -->
<div class="modal-footer" />
</div>
Questions:
1) Consider the <select>
elements in the controller's view above. #i_work
renders correctly with <option>
s just fine. #i_dont_work
renders a <select>
with no <option>
s. libraryTypes
seems to not be in scope inside <modal>
. Why is that, and how can I fix it?
2) Is there a better way to transclude specific content into multiple targets? Google's Polymer project provides <content />
with an optional [select]
attribute to provide multiple insert targets. Does Angular have anything like this? (See Polymer's website for more information.)