0

I have $scope.user = {} when I do this <input type="text" ng-model="user.name">the name in the input gets stored into $scope.user how do I get that value into another variable?

var myApp = angular.module('myApp', []);

    myApp.controller('WizardController', ['$scope', function($scope){

      $scope.user = {};
      $scope.displayName = $scope.user{'name'};

    }]);

2 Answers 2

3

I think you meant:

$scope.displayName = $scope.user.name

or

$scope.displayName = $scope.user['name']

Also, if you want to display the value of '$scope.user.name' somewhere in your html (which is what I assume you're trying to do) you can do something like this:

<h2>{{user.name}}</h2>

EDIT

If you want it to automatically refresh $scope.displayName in your view when you update $scope.user.name you'll need to add this to your controller:

$scope.$watch('user.name', function () {
    $scope.displayName = $scope.user.name;
});

However, there's probably very few good reasons to do it that way.

Fiddle: http://jsfiddle.net/HB7LU/3752/ (Updated from one in comment to include logging).

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

2 Comments

Actually that won't work as by the time that line of code $scope.displayName = $scope.user.name is executed the user property on the $scope has no name value, and changes to user.name will not be propagated to displayName.
Well, I'm pretty sure that if you were to log $scope.displayName at some point after changing $scope.user.name that it would represent the correct value but I agree that's probably not what is intended. I updated with a watcher (though I think this is probably usually a sign that something needs refactoring). Fiddle: jsfiddle.net/HB7LU/3750
0

If you want to put it in another variable you just have to make a new one.

$scope.newName = $scope.user.name;

The content will be put into the newName scope. Is that what you mean?

$scope.displayName = $scope.user{'name'}; I think you want to rewrite it to: $scope.displayName = $scope.user.name or $scope.user['name'];

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.