Nibble

Archive for October, 2014

Media picker directive for Umbraco v7 2

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.