简体   繁体   中英

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/

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

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;
        }
    });

you need to create your object like this

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM