0

I have utilized the Value() Module in my AngularJS App. I have declared and modified the Value, but I am not able to retrieve the modified or latest Value in a Controller.

  • Flow is as follows:

    1. STEP 1: Initialize the Value with .value("key": "value")
    2. STEP 2: Modify the Value in RUN Block. If I do console.log() in this STEP, I am getting the desired output. That means the Value is getting updated.
    3. STEP 3: Access that modified or latest value in Controller for further process.

I have mentioned the STEPS in the Code below.

app.module.js

(function () {
    "use strict";

    angular
        .module("app", [
            "app.authentication"
        ])

        //STEP 1: Initialize the Value.
        .value("errorCollectionObject", {})

        .run(getErrorCollection)


    function getErrorCollection($rootScope, $location, $http, errorCollectionObject) {

        $rootScope.$on('$routeChangeStart', function (event, next, current) {
            $http.get("../app/core/error-collection.json")
                .then(function (response) {

                    //STEP 2: Modify/Update the Value.
                    errorCollectionObject = response.data; 

                });
        });
    }
})();

login.controller.js

(function () {
    "use strict";

    angular
        .module("app.authentication")
        .controller("LoginController", LoginController)

    LoginController.$inject = ["errorCollectionObject"];

    function LoginController(errorCollectionObject) {

        var vm = this;

        //STEP 3: Use the Modified or Latest Value
        //But instead of getting the Modified value, I am getting the null Object {} that I initialized in STEP 1.
        console.log(errorCollectionObject);
        //Output is: {}

    }

})();

Any idea what is going wrong? Or am I implementing the concept in a wrong way? Any help will be greatly appreciated.

1 Answer 1

0

I am implementing the Value Module concept in the Wrong way. In my implementation method, the Value is not passed by Reference. And hence I am not getting the modified or updated Value.

In order to Pass the Value by Reference and to achieve the above-mentioned functionality, modify the Steps as below:

STEP 1:

var errObj = {errorCollection: null};
.value("errorCollectionObject", errObj)

STEP 2:

errorCollectionObject.errorCollection = response.data;

STEP 3:

console.log(errorCollectionObject.errorCollection);

You will get the Modified or Updated Value in Step 3. Hope it helps somebody. :)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.