AngularJS根据来自控制器的数据预填充输入字段

时间:2017-11-16 16:50:32

标签: javascript angularjs

我尝试使用控制器中的数据预填充表单。

简单代码看起来像

<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>

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

但它始终只预填充最后一个输入字段

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

3 个答案:

答案 0 :(得分:1)

您可以尝试使用此代码段

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

答案 1 :(得分:1)

在您的情况下,您使用第二个$scope.widget ($scope.widget = {title:'abc'})覆盖第一个($scope.widget = {content:'test'})

您必须以这种方式定义一个具有两个属性(标题和内容)的对象$scope.widget

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

答案 2 :(得分:0)

你需要像这样创建你的对象

left_parenth = math.count("(")
right_parenth = math.count(")")

total_parenth = right_parenth + left_parenth

if total_parenth % 2 != 0:
    if right_parenth > left_parenth:
        print("\nYou are missing a left parentheses '('")
    elif right_parenth < left_parenth:
        print("\nYou are missing a right parentheses ')'")

elif total_parenth % 2 == 0:
    print("\nYour equation has the correct amount of parentheses")
相关问题