Search code examples
angularjscode-injectioninjectprovider

Angular value provider not working


I'm injecting the value provider into my controller and I get an object, but when I try to read that object, by using .toString(), String(), or any other method, I only get [Object object] on the browser or the terminal. Did I miss something?

(function () {
    angular
        .module("myApp", [
            'ngRoute'
        ]);
})();

(function () {
    angular.module("myApp").constant('myValue', 3)
})();

(function () {
    angular
        .module("myApp")
        .controller('AllCtrl', ['myValue', setHome]);

    function setHome(myValue) {

        console.log("Value: " + myValue);

    }

})();


Solution

  • When you are passing an object from a templating engine like Razor, or ejs, you need to use the raw format of the object.

    In Razor, for example, it's .value("myValue", @Html.Raw([JSON serialized model])).

    In ejs it would be .value("myValue", <%- [JSON serialized object] %>)

    // *some .js file*
    (function () {
        angular
            .module("myApp", [
                'ngRoute'
            ]);
    })();
    
    // *in your .ejs file*
    (function () {
        // for ejs
        angular.module("myApp").constant('myValue', <%- jsonObject %>);
        // for Razor
        angular.module("myApp").constant('myValue', @Html.Raw(jsonObject));
    })();
    
    // *in another .js file*
    (function () {
        angular
            .module("myApp")
            .controller('AllCtrl', ['myValue', setHome]);
    
        function setHome(myValue) {
    
            console.log("Value: " + myValue);
    
        }
    
    })();