angular.js, can't edit dynamically created input fields

后端 未结 3 2093
梦如初夏
梦如初夏 2021-01-02 00:58

Using angular.js, I have a dynamic list of form fields I want to display to the user for editing (and later submission):

var app = angular.module(\'app\', []         


        
3条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-02 01:19

    SET answered why it's happening, but a work-around to achieve the desired behavior would be to maintain a separate array of your keys, and run ng-repeat off those keys. I added some text fields for testing to add more properties to $scope.fields

    You could use $watch to dynamically set the keys when the property count changes, if your requirements were that the field count may change.

    http://jsfiddle.net/aERwc/10/

    markup

    key value
    {{key}}:
    Add a field
    key:
    value:

    controller

    var app = angular.module('app', []);
    
    app.controller('Ctrl', function($scope) {
        $scope.fields = {
            foo: "foo",
            bar: "bar",
            baz: "baz"
        };
        $scope.fieldKeys = [];
    
        $scope.setFieldKeys = function() {
            var keys = [];
            for (key in $scope.fields) {
                keys.push(key);
            }
            $scope.fieldKeys = keys;
        }
    
        $scope.addField = function() {
            $scope.fields[$scope.keyToAdd] = $scope.valueToAdd;
            $scope.setFieldKeys();
            $scope.keyToAdd = '';
            $scope.valueToAdd = '';
        }
    
        $scope.setFieldKeys();
    });
    

提交回复
热议问题