Guidelines for setting up Kendo notifications using an angularjs service

I have successfully defined the Kendo notification in my Angular service. However, when I try to use it with the line uiService.notify.error("You missed some required fields.");, I am getting an error that says "Cannot read property 'show' of null". How can I resolve this issue?

HTML

 <span kendo-notification="notification" k-options="notifyOptions"></span>
<button class="k-button" ng-click="showInContainer()">Show in container</button>

controller.js

(function () {
    'use strict';
    angular
        .module('app')
        .controller('dataController', DataCtlr);

    DataCtlr.$inject = ['$scope', '$log', '$http', 'DataService','uiService'];

    function DataCtlr($scope, $log, $http, DataService, uiService) {
 $scope.showInContainer = function () {
        uiService.notify.error("You missed some required fields.");
    };
}

service.js

(function () {
    "use strict";

    app.factory("uiService", uiService);
    uiService.$inject = ["$rootScope", "$window", "$document"];

    function uiService($rootScope, $window, $document) {
        var svc = {
            settings: {},            
            notification: null, // kendo notification control
            notify: null
        };
        init();

        return svc;

        function init() {         
            initNotifications();

            $rootScope.ui = svc; // make available to the views
            $rootScope.notify = svc.notify; // for httpExceptionInterceptor
        }



        function initNotifications() {
            svc.notifyOptions = {
                templates: [{
                    type: "success",
                    template: "<div class='bg-success'><i class='fa fa-check' />#= message #</div>"
                }, {
                    type: "error",
                    template: "<div class='bg-danger'><i class='fa fa-exclamation-circle' />#= message #</div>"
                }, {
                    type: "info",
                    template: "<div class='bg-info'><i class='fa fa-info-circle' />#= message #</div>"
                }]
            }
            svc.notify = {
                success: function (message) {
                    svc.notification.show({ message: message }, 'success');
                },
                error: function (message) {
                    svc.notification.show({ message: message }, 'error');
                },
                info: function (message) {
                    svc.notification.show({ message: message }, 'info');
                }
            }
        }




    }
}());

Answer №1

To ensure there is always only one instance of the notification widget, I initialized it in my NotificationService and appended it to the body using jQuery. According to Kendos documentation, having multiple instances of the Notification widget displaying notifications at the same place on the page is not recommended as the notifications will overlap.

I also discovered that if the properties of the widget, such as notifyOptions, are undefined during initialization, the widget will fail silently. To avoid this issue, I prefer initializing the notification widget in the service with the id of an HTML element. If the element exists, it takes a reference to it; otherwise, it creates a default one.

In your service initialization (typescript example provided):

// init dom element 
var temp = $("#" + notificationElementId);
var domElement: Element;
if (temp.length > 0) {
    domElement = temp[0];
} else {
    $("body").append('<span id="' + notificationElementId + '"></span>');
    domElement = $("#" + notificationElementId)[0];
}

// create notification widget (so you have the reference in your service)
this.notification = new kendo.ui.Notification(domElement, this.notificationOptions);

Another issue arises when binding to the notification property in the controller scope but having the variable stored in the service. It is necessary to assign it to `svc.notification`, as mentioned by @dimodi previously.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the reason for needing to export the function when importing a module in an Angular appModule?

I came across the following code snippet @NgModule({ declarations: [ ... ], imports: [ RoutingModule, SharedModule, JwtModule.forRoot({ config: { headerName: 'Authorization', tokenGetter: () => lo ...

What could be causing the triggering of two AJAX requests in the given JavaScript code?

I have a code snippet that fetches data from the server. I want to trigger it on document.ready(). My expectation is that the first request is sent to the server, receives a response, and then the second request is made, and so forth. However, when I insp ...

Using checkboxes as a method, you can select from a pair

Here's my question: When using checkboxes, we can only choose one value. Check out this Plunk example <input type="checkbox" ng-true-value="Korman Juriy" ng-false-value="" ng:model="query.name"/> or <input type=" checkbox "ng - true - va ...

Conceal and reveal feature for multiple dynamic identifiers simultaneously

After submitting the form, I am dynamically creating buttons. <template name="workflow"> {{#each newaction}} <div class="btn-box" > {{> actioncardsubcontent}} <button type="button" class="cancelsub" >New Action</button&g ...

Give a radio button some class

<input id="radio1" type="radio" name="rgroup" value="1" > <label for="radio1"><span><span></span></span>1</label> <input id="radio2" type="radio" name="rgroup" value="2" > <label for="radio2"><span ...

Functionality of Ajax: Data fields containing numerous values

I'm confused about the data fields in the ajax function. Typically, the syntax for an ajax function looks something like this: $.ajax({ url: "/aaa/bbb/ccc", method: "SomeMethod", data: someData, success: function (res ...

What is the best method for showcasing numerous dropdown lists using JavaScript along with conditional if-else statements?

Hello everyone, I am currently new to javascript and I'm attempting to build a small web application using javascript. However, I am facing an issue with printing the drop-down list output. Could someone please assist me in resolving this problem? < ...

Issue regarding angularjs type definitions

I am facing an issue with installing typings for Angular and I need some guidance on how to resolve the error. Any suggestions or assistance would be greatly appreciated! Below is the error message that I encountered: ERROR in C:\Users\test&b ...

Experimenting with a sample post on a minimalist Node.js application using Mocha and Superagent

I trust you are having a splendid day. Currently, I am focusing on enhancing my TDD skills in Node.js. To practice, I have developed a minimalistic application that handles basic GET and POST requests. The app simply displays a straightforward form to the ...

Enter key triggering input change event is unresponsive in Internet Explorer

$("#inputBoxWidth").change(function() { var curValue = $("#inputBoxWidth").val(); alert(curValue); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form> <input type="text" id="inputBo ...

Interact with Circles Through Mouse Movements with d3.js Animation

I am currently utilizing the d3.js library and facing a challenge in meeting the client's requirements. The client has requested for "circles to turn black" and "follow" the mouse when hovered over. I am unsure if d3.js library supports such a featu ...

What could be the reason for the absence of a TypeScript error in this situation?

Why is it that the code below (inside an arbitrary Class) does not show a TypeScript error in VSCode as expected? protected someMethod (someArg?: boolean) { this.doSomething(someArg) } protected doSomething (mustBePassedBoolean: boolean) { /* ... * ...

The Failure of window.pushState in HTML 5 History

Looking to implement ajax loading for updating center content and URL without refreshing the page. Everything seems to be working fine except for the history management. It appears that window.pushState is not properly recording URLs or the popstate even ...

Incorporating an npm reference into a personalized node within Node-RED

As a novice in both the NodeRed and NodeJs/npm realms, I am embarking on the journey of creating a custom node for the first time. Despite my efforts to follow the official documentation on Creating your first node, I seem to have hit a roadblock. Everyth ...

Creating route paths within a single .js file

I'm a beginner when it comes to Node/Express, and I have a question about my app structure. Here is a simplified version of how my app is set up: /app /routes filter.js index.js app.js In my app.js file, I have defined my routes like th ...

Next.js optimizes the page loading process by preloading every function on the page as soon as it loads, rather than waiting for them to

My functions are all loading onload three times instead of when they should be called. The most frustrating issue is with an onClick event of a button, where it is supposed to open a new page but instead opens multiple new pages in a loop. This creates a c ...

Enabling the acceptance of repeated values in the ui-select element

ui-select does not permit the insertion of duplicate values in a select list item. However, I have a scenario where a user needs to input a value multiple times that will not be selected from the dropdown list. Is there a way to accomplish this using the ...

Discovering the precise location of the required() file

When using the require function in the `node` console with commands such as require('path') or require('assert'), how can I determine the absolute path of the file that was loaded? I have searched everywhere for a clear answer without ...

Internet Explorer's incompatibility with the window.location.href function

I'm having an issue with navigating to a new page using a callback from an AJAX post request specifically on Internet Explorer. Here is the code snippet causing the problem: $.ajax({ type: "POST", url: phpUrl, data: data, async: ...

Discover the position of an element in an array with the AngularJS filter

I have an array of data stored in $scope.domainRows: $scope.domainRows = [ { domainName: 'example1.com', domainDescription: 'example1.com desc'}, { domainName: 'example2.com', domainDescription: 'example2.com desc&ap ...