JackTheKnife
JackTheKnife

Reputation: 4144

AngularJS pre-fill input fields based on data from controller

I'm trying to pre-fill a form with a data from a controller.

Simple code looks like

<div ng-app="app" ng-controller="MainCtrl">
    <input name="widget.title" ng-model="widget.title">
    <input name="widget.content" ng-model="widget.content">
    <button ng-click="set('foo')">set to foo</button>
</div>

and

angular.module('app', [])
    .controller('MainCtrl', function($scope) {
        $scope.widget = {title: 'abc'};
        $scope.widget = {content: 'test'};
        $scope.set = function(new_title) {
            this.widget.title = new_title;
        }
    });

but it always pre-fill only last input field

JSFiddle: http://jsfiddle.net/b40nLuf2/

Upvotes: 0

Views: 1587

Answers (3)

Dakota
Dakota

Reputation: 525

you need to create your object like this

$scope.widget = {
         title: 'abc',
          content: 'test'
};

Upvotes: 0

br1
br1

Reputation: 377

In your case, you overrides the first $scope.widget ($scope.widget = {title:'abc'}) with the second ($scope.widget = {content:'test'}).

You have to define one object $scope.widget with two attributes, title and content, in this way:

angular.module('app', [])
    .controller('MainCtrl', function($scope) {
        $scope.widget = {
            title: 'abc',
          content: 'test'
        };
        $scope.set = function(new_title) {
            this.widget.title = new_title;
        }
    });

Upvotes: 1

Vishvadeep singh
Vishvadeep singh

Reputation: 1663

you can try this code snippets

angular.module('app', [])
    .controller('MainCtrl', function($scope) {
        $scope.widget = {title: 'abc',content: 'test'};
        $scope.set = function(new_title) {
            this.widget.title = new_title;
        }
    });

JSFIDDLE : click here to see

Upvotes: 1

Related Questions