1

I have defined $rootScope variable by using following code:

$rootScope.userDetails = function () {
        $http.post($account + '/feedbackdiv')
            .success(function (res) {
                $rootScope.userData = res.userData;
            });
    };
    $rootScope.userDetails();

Now, userData is accessible from everywhere. Now I tried to assign the userData.FirstName value to text field like this:

<input type="text" class="form-control museo_sans300" id="fName" 
  placeholder="First Name" name="fName" minlength="1" ng-model="fName" 
  ng-init="fName = userData.FirstName" required="required">

But this didn't initial value in the text field. I also checked that when I give static value to ng-init it works correctly, like, ng-init ="fName = 'test'" Furthermore I also verified that I am getting value of userData.FirstName. Please provide a solution to initialize this input text field.

1 Answer 1

1

There is no reference between fName and userData.FirstName after initial assignment fName = userData.FirstName. Also ngInit is not going to be run again on every digest loop. So when later userData.FirstName is populated primitive fName is not going to be updated. This is expected javacript behavior not related to Angular.

So you either use userData.FirstName directly as model:

<input type="text" class="form-control museo_sans300" 
       id="fName" placeholder="First Name" name="fName" minlength="1" 
       ng-model="userData.FirstName" 
       required="required">

Or you will need to manually set fName in controller once userData is loaded.

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

5 Comments

if I bind it directly as the model, the changes also effects the $rootScope value, which is not desirable.
When I tried to manually set value of $scope.fName = $rootScope.userData.FirstName; in Controller, it gives undefined value.
You need to set in when it's available, in http success callback. Or you need watcher.
I have tried Variant 1 and it works great for me. Thanks. But I will also try watcher variant because I think it will be more flexible.

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.