Nibble

Media picker directive for Umbraco v7

In the previous post I showed how you can use the media picker in your custom backoffice pages, now I’ve reworked the example by using an Angularjs directive. So with a directive we’ll end up with a component that is easily reusable accross different pages.

The Directive

1 angular.module("umbraco.directives") 2 .directive(umbMediaPicker, function (dialogService, entityResource) { 3 return { 4 restrict: E, 5 replace: true, 6 templateUrl: /App_Plugins/Example/umb-media-picker.html, 7 require: "ngModel", 8 link: function (scope, element, attr, ctrl) { 9 10 ctrl.$render = function () { 11 var val = parseInt(ctrl.$viewValue); 12 13 if (!isNaN(val) && angular.isNumber(val) && val > 0) { 14 15 entityResource.getById(val, "Media").then(function (item) { 16 scope.node = item; 17 }); 18 } 19 }; 20 21 scope.openMediaPicker = function () { 22 dialogService.mediaPicker({ callback: populatePicture }); 23 } 24 25 scope.removePicture = function () { 26 scope.node = undefined; 27 updateModel(0); 28 } 29 30 function populatePicture(item) { 31 scope.node = item; 32 updateModel(item.id); 33 } 34 35 function updateModel(id) { 36 ctrl.$setViewValue(id); 37 38 } 39 } 40 }; 41 });

The Template

1 <div> 2 <ul class="unstyled list-icons" ng-if="node"> 3 <li> 4 <i class="icon icon-delete red hover-show pull-right" ng-click="removePicture()"></i> 5 6 <i class="icon {{node.icon}} hover-hide"></i> 7 {{node.name}} 8 </li> 9 </ul> 10 <ul class="unstyled list-icons"> 11 <li> 12 <i class="icon icon-add blue"></i> 13 <a href ng-click="openMediaPicker()" prevent-default> 14 Select 15 </a> 16 </li> 17 </ul> 18 </div>

Using the directive

First we of course need to make sure to update the package manifest and include the directive in the array of js files. Then the directive can be used as

1 <umb-media-picker ng-model="person.pictureId" />

This directive has been added to the example project.

3 Comments so far

  1. Warren Buckley on October 3rd, 2014

    A great example Tim on an Angular Directive and showing re-usability with a simplier single DOM element in the end. However this to me makes sense to be in the core so that a common design language/pattern is available and that package developers/umbraco extenders can create a consistant & nice looking UI in keeping with Umbraco’s design goals.

    Just a thought, however great work Tim :-)

  2. Jamie Pollock on October 3rd, 2014

    Nice, I tried to a generic umb-picker directive when trying to use the RTE in a custom section. However it may have come off a bit complex.

    You can see the gist of it here (https://gist.github.com/jamiepollock/1b5cc40e7f59bd06ba42)

  3. Hi,I check your blog named “Media picker directive for Umbraco v7 - Tim Geyssens, Umbraco developer” regularly.Your writing style is witty, keep up the good work! And you can look our website about مران النادى الاهلى.

Leave a Reply