Thursday 16 March 2017

Pass a Parameter to UI-Router From Constructor

I have read a lot about using resolve to do something like this but I cannot seem to get it to work (possibly because I don't really understand how it is working).

So I have a controller which processes a variable which we will call xName. I want to be able to pass this variable into my appUIRouter.js to use with my state (for use with other states and for titles).

Things I have tried...

  1. Reference

appUIRouter.js

// get resolve data for use throughout all states.
var resolveParams;
app.config(function($stateProvider, $urlRouterProvider) {

    $stateProvider.state("tasking", {
         url: "/tasking",
         templateUrl: "tasking.html",
         controller: "taskingController",
         controllerAs: "taskingCtrl"
        },
        resolve: {
            messages: function(taskService) {
                resolveParams = taskService.getMessages();
        },
        data: { pageTitle: resolveParams } // Doesn't work
    }
}

taskingController.js

function createData() {
    var theData;
    ... // Calculations and stuff
    taskingService(theData);
}

function taskingCtrl(messages) {
    this.messages = messages; // <-- to be sent to resolve
}

This didn't work I also tried switching in the UIRouter...

        resolve: {
            messages: function(taskService) {
                return taskService.getMessages();
        },
        data: { pageTitle: messages } // Still Doesn't work
    }
}

  1. Using $scope.$emit to send to a directive inside the UIRouter

appUIRouter.js

// get resolve data for use throughout all states.
var resolveParams;

app.config(function($stateProvider, $urlRouterProvider) {

    $stateProvider.state("tasking", {
         url: "/tasking",
         templateUrl: "tasking.html",
         controller: "taskingController",
         controllerAs: "taskingCtrl"
        },
        data: { pageTitle: resolveParams } // Doesn't work
    }
}

app.directive('finding', ['$rootScope', function($rootScope) {
    return {
        link: function() {
        $rootScope.$on('receiveData', function(event, data) {

            console.log(data.stuff); // <-- Is the correct data.
            resolveParam = data.stuff;
        });
    }
}]);

taskingController.js

function createData() {
    var theData;
    ... // Calculations and stuff
    $scope.$emit('receiveData', { stuff: theData });
}

This sends the data to the directive in the UIRouter but it doesn't seem to be properly used such as when I want to use it in a title.

Am I going about this wrong? Apologies as I am new to Angular and am trying to figure out how things work.



via user3684399

No comments:

Post a Comment