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

Ways to access a field value in SAPUI5

As I delve into OPENUI5/SAPUI5, I'm faced with the task of accessing data for the controls I've implemented. For instance: <Label text="Amount" /> <Input id="inputAmount" value="{Amount}" /> <Text id="lblCurrency" text="USD" > ...

Issues arising with shadows in THREE.js

I've been struggling to get shadows to work in this fiddle despite trying various configurations. I've looked at other similar questions, tried all the suggested solutions, but still nothing... My current settings include: this._box.castShadows ...

"Emphasizing the Html.ActionLink menu for improved user navigation and

Currently, I am facing an issue with my menu. I want to clear previously visited links while keeping the current one styled as a:visited in CSS. Although I have attempted to achieve this, unfortunately, the code is not functioning properly. Here is what I ...

Is it necessary for material-ui useStyles to use the entire props object?

Perusing through the documentation, it suggests that in order for our component to accommodate style overrides using classes, we are advised to provide the entire props object to the useStyles hook: function Nested(props) { const classes = useStyles(prop ...

Trouble updating Kendo DropDown in Internet Explorer

Having an issue with updating a Kendo DropDownList through a javascript function. It works fine in FireFox and Chrome, but not in Internet Explorer. @(Html.Kendo().DropDownList() .Name("myDDL") .HtmlAttributes(new { style = "width: 320px" }) . ...

Using multiple conditions in an angular ngif statement to create a variable

Is it possible to assign the result of a function to a variable in Angular (13) within the .html section of a component, specifically with multiple conditions in ngIf? <div *ngIf="let getMyVar() as myVar && isVisible && isClean" ...

Encountered a problem while trying to install using npm install

Encountering an error while running npm install on Ubuntu 12.04: Here is a snippet from my npm-debug.log showing where the errors occur: ... (contents of npm-debug.log) ... This is my package.json: { "name": "www", "version": "0.0.1", /"p ...

Executing an Ajax request that invokes a PHP function

After receiving valuable information in response to my previous inquiry through this link, I took the initiative to create a code that would notify me via email if it is discovered on another website. Below is the JavaScript code designed for potential co ...

The AJAX call is failing to update the state data in my React component

I've recently delved into ReactJS and encountered an issue regarding setting state while using an AJAX request. The AJAX call successfully communicates with the server, receiving a 200 code response, indicating that the API request functions properly ...

steps to activate button once the form is validated

Can you provide guidance on disabling and enabling a button when the form is valid? I have several conditions in my form: Name on Card: Should only contain English alphabetic letters. Card Number: Must consist of exactly 16 numbers. Expiration Month: A ...

Determining Velocity of an Object in Three.js

Can anyone help me figure out how to calculate an object's velocity in three.js? I've checked the Object3D documentation but can't seem to find anything related to velocity. Appreciate any assistance, ...

Setting up CloudKitJS Server-to-Server Communication

I'm struggling to make this work. I keep encountering the following error message: [Error: No key provided to sign] Below is my configuration code: CloudKit.configure({ services: { fetch: fetch }, containers: [{ containerIdentifier: & ...

How can I retrieve an attribute from another model in Ember using the current handlebar in the HTML file?

I'm attempting to achieve the following: {{#if model.user.isAdmin}} <div> My name is {{model.user.name}} </div> {{/if}} within a handlebar that is being used in a controller unrelated to users: <script type="text/x-handlebars" data- ...

Customize Vuetify Menu by adding a unique custom keypad component for editing text fields

I am currently developing an app using vuetify, and I am encountering some challenges with the v-menu feature. The issue arises when I click on a text input field, it triggers the opening of a v-menu. Within this menu, there is a custom component that I h ...

Ways to initiate SVG animations using Angular Component functions?

I am currently working on a project where I want to incorporate an animation that reflects the sorting process of an array of numbers. However, despite successfully sorting the numbers in the array, I am facing challenges with triggering the animations. I ...

Issue with updating state following data retrieval in React hooks

Recently, I've been experimenting with an API and working on a React application for data display. However, I encountered an issue while setting the state using the setState method of React Hooks after sending my information through a form request via ...

Please ensure to refresh the page after confirming the alert box by clicking OK

Is it possible to clear certain inputs on my Magento store's checkout page when an alert box is displayed and the user clicks OK? Unfortunately, I do not have control over the JavaScript alert. Therefore, I thought of implementing a script that can d ...

I am facing an issue where the table in my Laravel Vue component is not displaying the data from

Recently, I've been diligently following an instructional series on VUE applications by a highly recommended YouTuber. Every step was meticulously executed until I hit a roadblock out of nowhere. The data from my database refuses to display on the fro ...

Utilize prop-types inheritance when a component is rendered via props

Is it possible to inherit prop-types when a component is rendered via the parents prop, without direct access to 'ChildProps' and 'Props' interface? Parent Component interface ChildProps { counter: number; setCounter: React.Dispat ...

The chat text will automatically scroll down, displaying information loaded from the database

Is there a way to ensure that chat text always remains scrolled to the bottom of the chat? I have tried multiple tutorials and examples from Stack Overflow, but none seem to work for me. Currently, my chat text overflows the textarea when there are too m ...