0

According to best practices I read about, in my controller, I assign a model to the $scope rather than assignging multiple separate values to $scope:

  .controller('TestCtrl', function AboutCtrl($scope, $http) {

    var model = {
        name: 'Bob',
        address: 'Squaresville'
        }
    };

    $scope = model;
})

And in my template:

<input type="text" ng-model="model.name" /> {{model.name}}
<input type="text" ng-model="model.address" /> {{model.address}}

But when the page initially loads, the text boxes have no value. But as I type, the matching {{...}} tags get updated.

Why doesn't the initial value get updated?

2
  • 1
    remove model. in your markup Commented Jun 30, 2014 at 14:21
  • 1
    you are setting your $scope to model ($scope=model). You should be doing $scope.model = model; Commented Jun 30, 2014 at 14:25

2 Answers 2

5

Do this instead:

$scope.model = model;

Or just define it that way:

$scope.model = {
    name: "Bob",
    address: "squaresville"
}
Sign up to request clarification or add additional context in comments.

3 Comments

Woo!, thanks. But do you know why my way did what it did (allow updates but not initial values?)
You crushed the $scope variable, shouldn't be doing that :)
@Cabbagesocks Just remember when referring to this value in your markup to include model so... <input ng-model="model.name"> and not <input ng-model="name">
2

There is a shorter way to do what you want:

$scope.model = {
        name: 'Bob',
        address: 'Squaresville'
        };

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.