0

I'm not sure what the term is, but I need to give the same data to all components in my app. Here's the basic structure of my app:

BeforeAngular.js

function DataModel(json){
    this.name = json.name || "No name"
}

//// JQuery ////
function getDataModel(name) {
    return $.get(baseURL + "data-model/" + name).then(response => {
        return new DataModel(response)
    })
}

AppSetup.js

var app = angular.module('MyApp', ['ui.router', 'ngResource', ...]);

app.config(function($stateProvider,$httpProvider,$urlRouterProvider,$sceProvider) {
    $sceProvider.enabled(false)

    // Each of these components need `getDataModel()` - how can I do that once and send it to all of them with Angular
    states = [
        { 
            name: 'Interactor', 
            url: '/interactor',
            component: 'interactorcomponent'
        },
        {
            name: "otherwise",
            url: "*path",
            component: "viewMDLcomponent"
        }
    ];

    states.forEach(state => $stateProvider.state(state))

    $httpProvider.defaults.useXDomain = true;
    delete $httpProvider.defaults.headers.common['X-Requested-With'];
}

ViewMDLComp.js

angular.module("MyApp").component("viewMDLcomponent", {
    templateUrl: "html/View_MDL.html",
    controllerAs: "c",
    controller: [..., View_MDL_Controller]
})

function View_MDL_Controller($http,$timeout,$filter,$log,$q,$sce,l,FileSaver,Blob) {
    var c = this

    $q.when(getAllDataModels().then(r => {
        console.log("getAllDataModels");
        c.allMisDataModels = r
    })
}

So how Can I run something in Angular that compiles before my components, and feeds them the data they need?

Travis Heeter
  • 13,002
  • 13
  • 87
  • 129

1 Answers1

0

Inside your jQuery function for getting the data when you resolve your promise assign the result inside a global variable attached to the window object. Like:

window.myAppDataModel = new DataModel(response);

Then bootstrap your angular application after you resolved this getDataModel function.

Then inside angular define a constant assigning it to this value:

myApp.constant('MY_DATA_MODEL', window.myAppDataModel);

Then inject this constant inside all the services/controllers where you need it.

Even if this should work, my suggestion is to bring this logic inside in angular inside a service, and in the resolve block of your states (or just at the bootstrap if you need that once) perform your request and store the value inside the service. Then inject the service and access the data where you need.

quirimmo
  • 9,800
  • 3
  • 30
  • 45