AngluarJS 1.5 component fails to respond to broadcasted events sent from $scope

I am experiencing a challenge and struggling to find a solution. Below is the code snippet of a component I am working on:

    (function () {
    'use strict';

    // Usage:
    // 
    // Creates:
    // 

    myApp
        .component('navbar', {
            //template:'htmlTemplate',
            templateUrl: 'app/components/navbar/navbar.partial.html',
            controller: ControllerController,
            bindings: {
                progress: '<'
            },
        });

    ControllerController.$inject = ['$scope','$rootScope','changeState'];
    function ControllerController($scope,$rootScope,changeState) {

        var $ctrl = this;

        $scope.$on('state-changed',function(event,args){
            console.log(args);
        });




        $ctrl.$onInit = function () { };
        $ctrl.$onChanges = function (changesObj) { };
        $ctrl.$onDestory = function () { };
    }
})();

The event 'state-changed' gets triggered by $transitions.onSuccess in ui-router 1.0 Beta. Here is the relevant code:

var myApp = angular.module('myApp', ['ui.router']);

myApp.controller('appCtrl', ['$scope', '$state', 'formDataService', '$timeout', '$transitions','changeState','$transitions',
        function ($scope, $state, formDataService, $timeout, $transitions,changeState,$transitions) {

        changeState.go('1');
        $scope.stateByFar = 1;

        $scope.currentState = function(){
            return $state.current.name;
        };

        $scope.updateStateByFar = function(){
            if (parseInt($scope.currentState())>$scope.stateByFar)
                $scope.stateByFar=parseInt($scope.currentState());
        };



            $transitions.onSuccess({to: '*'}, function(){

                $scope.updateStateByFar();
                console.log($scope.stateByFar);
                $scope.$broadcast('state-changed',{currentState: $scope.currentState(),
                                                    stateByFar : $scope.stateByFar});

            }
            );




    }]);

[EDIT] The broadcast works correctly, but it does not work on the first state.go call. When the main module runs, the first instruction is: $state.go('1'); and the initial state.go cannot be detected. Subsequent state.go calls are successfully listened for.

Answer №1

If you're facing a similar issue to mine, I hope sharing my experience can assist you. You can find a detailed description of the problem I encountered and the solution I discovered here.

In essence, I encountered some difficulties while using $transitions and noticed that in version 1.0.0.beta1, the to and from parameters were not functioning as expected.

Instead of:

$transitions.onSuccess({to: '*', form: '*'}, function(){});

I now utilize:

$transitions.onSuccess({}, function(){
    if($state.current.name == 'myState') // do stuff
});

Answer №2

Let me highlight four key points:

1) The use of '*' as a glob pattern only matches states at the root level, not child states. To include child states, utilize double star '**'. Unfortunately, the documentation on ui-router globs is fragmented and lacking in detail.

Alternatively, you can rely on the default criteria which already covers any state by using onSuccess({}, ...).

You can find more information on this at

All properties are optional. If any property is omitted, it is replaced with the value true, and always matches.

2) When creating a hook in a controller, remember to unregister that hook when the controller scope is destroyed.

var deregisterFn = $transitions.onBefore(...)
$scope.$on('$destroy', deregisterFn);

3) In case a transition is ongoing before your controller initializes (and prior to registering your onSuccess hook), the initial transition will not be captured. You can tap into the in-progress transition promise through $state.transition && $state.transition.promise

4) While the deprecated $stateChange* events are still accessible, you need to actively choose to use them. Refer to

For detailed guidance on migrating to version 1.0, consult this resource:

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

The issue of notifications not displaying in a Cordova iOS app due to Device.uuid plugins

Having an issue with my Cordova iOS app. I rely on the UUID functionality frequently, but it seems to be malfunctioning. The app gets stuck at the alert that displays it. onDeviceReady: function() { alert("On device Ready"); // This is working fine ...

Having trouble properly removing an item from an array using splice() function

I'm facing an issue with an array where I need to remove a specific object. I attempted using the splice() method, but upon implementation, it ends up removing all objects except the one that was found. Here's a snippet of my JavaScript code: On ...

Submitting data to an external PHP file using the JavaScript function $.post

Having issues with the PHP page function ajaxFunction(){ var ajaxRequest; try{ ajaxRequest = new XMLHttpRequest(); } catch (e){ try{ ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try{ ajaxRequ ...

Directive ng-click not executing as expected

Currently, I am developing an Angular application that involves a controller named visualization and a directive named force-layout. Within the HTML template of the directive, I have implemented three buttons with corresponding functions attached to them. ...

Creating a complex user interface in Angular using multiple nested views with the help of Angular

Exploring the nested views functionality of the ui-router plugin has presented me with a challenge that I am struggling to resolve. The problematic code can be accessed at this link: http://jsfiddle.net/3c9h7/1/ var app = angular.module('myApp&apos ...

Gradient in Half Circle With JavaScript

How can I achieve a gradient effect within a circle using the following initial code: HTML: <div class="progresss"> <div class="barOverflow"> <div class="bar"></div> </div> <span>10</span>% </d ...

Guide to organizing a calculated attribute in vue.js

I'm struggling with organizing the already computed array of results. Within Vue, I have successfully filtered images based on their ratio. Now, my goal is to sort these filtered results by date, name, or any other possible category. Although I atte ...

Adding complex JSON format to an HTML table involves formatting the data correctly and then using

Utilizing AJAX, I fetched a JSON response and am now looking to map the JSON data into an HTML table structured like this: { "records": [{ "type_id": 000001, "type_desc": "AAAAAA", "type_createby": "Adam" }, { "type ...

Searching for the Magic Index using Binary Search

Currently working on mastering binary search and encountering difficulties while trying to use it to locate the "magic index" within an array, where the magic index is defined as A[i] == i. While I have come across some Java implementations using recursio ...

`The value of an array containing specific class elements is lost when accessed within a setTimeout

I've come across an issue while using a JavaScript file to hide several divs all sharing the same class name. The program successfully hides the divs, but when I try to make them visible again after a certain number of seconds, the array of elements b ...

Using AJAX in Django to detect fields with JavaScript

I am currently working on a model: class Name(models.Model): name = models.CharField(max_length=255) project = models.CharField(max_length=255) story = models.CharField(max_length=500) depends_on = models.CharField(max_length=500, ...

The output from the Node.js child_process.exec command returned null for stdout, yet stderr was not empty

I'm currently working with a simple code that runs java -version in the command line to check if Java is installed on the user's system. Interestingly, when I execute this code, the stdout does not display anything, but the stderr shows the expe ...

An unexpected error occurred during page generation. Any relevant console logs will be shown in the browser's terminal window

Encountered a RangeError: Maximum call stack size exceeded while compiling this web app in the browser. The error occurred on my header tag and sometimes on the return tag. What should I do? export default function Header() { return ( <> ...

Issue with nivo-lightbox not opening upon clicking image

I have diligently followed the instructions to set up this JavaScript plugin, but unfortunately it doesn't seem to be functioning properly. The plugin I'm using can be found here: All the links to the CSS, theme, and JavaScript files are display ...

Retrieving text content from a file using React

I've been experiencing difficulties with my fetch function and its usage. Although I can retrieve data from the data state, it is returning a full string instead of an array that I can map. After spending a few hours tinkering with it, I just can&apos ...

Issue with Mouse Hover not functioning properly across various 3D objects

Trying to create a 3D line chart? Check it out Here Currently, the points and lines are working fine. However, I only want to detect mouse hover on the points (spheres) and not on the lines or grid. To achieve this, I have segregated all elements into dif ...

use the fetch api to send a url variable

I'm struggling to pass a URL variable through the API fetch and I can't seem to retrieve any results. As a newcomer to Javascript, any help is greatly appreciated. //Get IP address fetch('https://extreme-ip-lookup.com/json/') .then(( ...

Troubleshooting problem with the oninput function of a custom JavaScript element

Assume I have a unique requirement to trigger a function within a custom element. The goal is to update text in the element only when a slider is moved within that specific element. Here's an example implementation in the main.js file: class Oninput ...

Tips on how to eliminate items from a list that do not include a specific character

I need help with a list that has a specific format /listing/vasita-otomobil-volkswagen-boyasiz-2016-passat-variant-1.6-tdi-dsg-higline-sunroof-hayalet-819608311/detail,#,#,,/listing/vasita-otomobil-volkswagen-boyasiz-2016-passat-variant-1.6-tdi-dsg-higline ...

Obtaining the variable from the exec function in Node.js can be achieved by capturing

I am trying to access the values of variables w1 and h1 outside of the exec function and display them using console.log. exec(command, function(err, stdout, stderr) { var resolution = stdout.split("x"); w1 = resolution[0]; h1 = resolution[1]; ...