Creating Umbraco custom helper in AngularJS

Introduction

The entire Umbraco back-office panel is built around AngularJS which allows for easy extension and modification of basic functionalities. For the work to be effective, you should use a ready set of filters, services, and directives that allow you to speed up the development time. See Umbraco 8 Backoffice UI API Documentation to discover the full list of components and functions.

However, very often in everyday work, we have to create our own service in angular to encapsulate some functionality and make the code cleaner.

I will present how to quickly create a custom service called ‘storageHelper’ that is ready to inject and use directly in any controller.

Using new service in the controller

function testController($scope, storageHelper) {

    $scope.vm = this;
    
    function init() {

        storageHelper.sayHello();       
    }

    init();
}

angular.module("umbraco").controller("Umbraco.TestController", testController);

Creating the service

All example-related files can be stored inside the plug-in directory where the new service will be used, for the purpose of this text let’s assume “~/App_Plugins/CustomService” directory.

First, let’s create a “~/App_Plugins/CustomService/storageHelper.js” file that contains the core implementation of the ‘storageHelper’ service. 

Then, go to a new file, extend the ‘umbraco.services’ module, create a factory recipe called ‘storageHelper’, and expose a simple method named ‘sayHello’ as follows:

(function () {

    angular.module('umbraco.services').factory('storageHelper', function () {
        return {
            sayHello: function sayHello() {
                alert('Hello from storageHelper');
            }
        };
    });
})();

Registering the service with package.manifest

Now, a new service should be included in package.manifest file to load all javascript dependencies during the startup of the application. Add a file named ‘package.manifest’ to the ‘App_Plugins’ folder, containing the following JSON configuration pointing to storageHelper.js file.

{
  "javascript": [
    "~/App_Plugins/CustomService/test.controller.js",
    "~/App_Plugins/CustomService/storageHelper.js"
  ]
}

Common pitfalls

Uncaught SyntaxError: In strict mode code, functions can only be declared at top level or inside a block

Error: [$injector:undef] Provider ” must return a value from $get factory method

Final thoughts

Once the ‘storageHelper’ function is properly registered and added to the angular module we can take advantage of the dependency injection benefits. In other words, it’s possible to add storageHelper as a parameter to the controller constructor and the angular engine will inject an instance.

Similar Posts