0

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/

3 Answers 3

1

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;
        }
    });
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

you need to create your object like this

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

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.