Exploring the reach of scope in a directive

Managing a controller responsible for fetching event JSON data, updating the DOM with data if available, and displaying an error message if no data is found:

//Controller.js
myApp.controller('EventsCtrl', ['$scope','API', function ($scope, api) {
    var events = api.getEvents(); //events: {data: [], error: {message: 'Some message'}}
}]);

//Directives.js
myApp.directive('notification', function () {
    return {
        restrict: 'A',
        link: notificationLink
    };
});
/**
 * Displaying notification messages
 */
var notificationLink = function($scope, element, attrs) {
    $scope.$watch('notification', function(message) {
        element.children('#message').text(message);
        element.slideDown('slow');
        element.children('.close').bind('click', function(e) {
            e.preventDefault();
            element.slideUp('slow', function () {
                element.children('#message').empty();
            });
       });
    });
};
//Services.js
...
$http.get(rest.getEventsUrl()).success(function (data) {
        // Do something with data
    }).error(function (data) {
        $window.notification = data;
    });

Encountering issues where the element changes are triggered but $window.notification remains empty.

Edit: Attempted to address this using $watch functionality.

Edit: Combining both sets of html into one controller resolved the DOM manipulation issue with the help of $watch(). Grateful for the assistance provided!

Answer №1

Make sure to assign the response from your HTTP request to a variable within your controller's scope. After that, you can monitor changes to this variable in your directive.

myApp.controller('EventsCtrl', ['$scope', 'API',
    function ($scope, api) {
        $scope.events = api.getEvents(); //events: {data: [], error: {message: 'Some message'}}
    }
]);

//Directives.js
myApp.directive('notification', function () {
    return {
        restrict: 'A',
        link: notificationLink
    };
});

var notificationLink = function (scope, element, attrs) {
    scope.$watch('events', function (newValue, oldValue) {
        if (newValue !== oldValue) {
            if (scope.events.data.length) {
                //Display Data
            } else {
                //Display Error
            }
        }
    });
};

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 strategies can I use to enhance the efficiency of my code using AngularJS?

After conducting extensive research, I am still unable to find a solution or comprehend the code written by someone else - it simply does not work. As a result, my codebase has grown significantly. I am interested in optimizing my code using AngularJS func ...

Using React to trigger a child component's function upon clicking a tab

I need assistance with creating a React app that includes two tabs (Tab1, Tab2). When Tab2 is clicked, I want a message to appear in the console saying 'Function A is called'. Unfortunately, the code I have currently does not display the message ...

Why am I unable to retrieve data using jQuery and PHP?

I'm working with a PHP form that involves checkboxes: <form action="" method="post" id="CheckBoxForm"> foreach ( $results as $result ) : <input type="checkbox" class="chk" id="check_list[]" value="'.($result->meta_value).&a ...

Tracking the email field in a React form with refs

Hey there! I'm a music engineer working on my own personal website using React. I'm currently facing an issue with creating a contact form that allows users to input a subject in a text field, a message in a textarea, and then click a "reach out" ...

definition of a function with another function

I'm curious about whether it's considered a good practice in JavaScript to define a function within another function. Take a look at this code snippet: module.exports = function() { function foo() { // do something } ... foo() .. ...

Capturing Key Events on Canvas in Vue.js

When using Vue 2.5, I encountered an issue with a canvas element that has a key event listener: <template> <canvas v-on:keyup.esc="abortThing"></canvas> </template> <script> export default { methods: { abortTh ...

Is there a way to pre-load the data prior to the component rendering in ReactJS?

The main goal of my project is to retrieve data from the Google Analytics API and display it as a list. Although I am able to successfully fetch the data from the API, I am encountering an issue when passing it to another component. While I can view the da ...

Vue alert: The instance does not have a defined "hp" property or method, but it is referenced during rendering

Below is the code snippet that I am currently working with: var example1; var hp = ["p"]; document.addEventListener("DOMContentLoaded", function(event) { hp = ["x"]; example1 = new Vue({ el: '#example-1', data: { iLoveMysel ...

Instructions on generating a fresh Ethereum or Solidity contract for every test using JavaScript and Truffle

overview After developing an Ethereum smart contract using the Solidity language, I utilized Ganache to deploy my contract for testing purposes. However, in order to conduct tests effectively, I need to create a new instance of my contract using JavaScrip ...

The speed at which Laravel loads local CSS and JS resources is notably sluggish

Experiencing slow loading times for local resources in my Laravel project has been a major issue. The files are unusually small and the cdn is much faster in comparison. Is there a way to resolve this problem? https://i.stack.imgur.com/y5gWF.jpg ...

What is the method for retrieving all 'name' values within a JSON array?

I am currently working on a project using Angular and I have a JSON file. I need to extract all the 'name' values from the array. Ideally, the output should look something like this: ['Sony', 'Apple', 'Sony'] JSON: ...

Guide on accessing an array within a JSON object?

I have the following JSON object: [ { "comments": [ { "created_at": "2011-02-09T14:42:42-08:00", "thumb": "xxxxxxx", "level" ...

Height of the Accordion List

I have a code snippet below for an accordion list that I put together. I initially set the height for all the heading boxes to be uniform, but it seems like box A is displaying larger than the others. Can you help me figure out what went wrong? Any suggest ...

What is the best approach to building this using Angular?

Greetings, this marks the beginning of my inquiry and I must admit that articulating it correctly might be a challenge. Nevertheless, here's my attempt: Within the following code snippet, there lies an element that effectively fills up my designated ...

How can you create a unique record by appending a number in Javascript?

Currently, when a file already exists, I add a timestamp prefix to the filename to ensure it is unique. However, instead of using timestamps, I would like to use an ordinal suffix or simply append a number to the filename. I am considering adding an incr ...

Comparing the positions of elements in Selenium WebDriver with PHP

One of the elements on my webpage serves as a button that reveals a drop-down menu. Due to various factors affecting the page layout, there were some alignment issues between the button and the menu until a few bugs were fixed. I am now looking for a way t ...

Having trouble formatting an AJAX POST request properly

Despite my best efforts, I continue to encounter the dreaded 500 (Internal Server Errors) every time I try to execute a POST request to https://rates.tradelanes.us/bankaccount/record/create. I suspect it has something to do with the format of my data. Howe ...

"Efficient Implementation: Expo React Native Utilizes Custom Font Loading One Time Only

Hello everyone, I'm a newcomer here and I'm currently using Expo to build a react native app. My goal is to implement custom fonts in my project. I've gone through the documentation which can be found here. However, I'm facing an issue ...

Enhancing ajax requests with headers in Ember.js

My goal is to configure request headers for my emberjs application. However, when setting it up in the initializer, the client_id appears as [object Object] instead of the actual value. This is the initializer that runs when the application starts. Apikey ...

Issue - The module ./en.json could not be located when using the vue-i18n plugin

I recently integrated the i18n plugin into my existing Vue project to add localization. After following all the installation instructions from various sources (such as here), I made sure that each locale has its own file under /src/locales with the correct ...