在ng-value(单向)和ng-model(双向)绑定之间切换输入

时间:2015-10-07 23:38:25

标签: angularjs

我有一个html input字段列表,可以绑定到他们的支持json内容字段(双向通过ng-model),或者从html中的选定对象获取它们的值'select'(单向通过ng-view),或需要在两种表格之间切换。我甚至不确定后者是否可能,因为我是angularjs的新手,这就是这个问题的关键所在。

我可以为切换绑定输入文本正确设置初始input绑定,如果它具有null内容,则绑定到选择列表,但如果它具有非null内容,则绑定那个。我还可以为每个设置一个checkbox来跟踪它是从用户那里获得输入,还是从select列表中获取。

我需要做什么:如果用户开始手动输入值(或取消选中'使用选择列表'checkbox),它会切换到文本内容字段的绑定。当用户检查“使用选择列表”select时,它还需要切换回绑定到checkbox

<div ng-app="myApp">
    <div ng-controller="myCtrl">
        <label for="ddlSelectionList">Select from list:</label>
        <select id="ddlSelectionList" ng-model="selectedRow" ng-options="row as row.name for row in selectionList"></select>
        <div ng-repeat='text in texts'>
            <label for='txt{{text.id}}'>{{text.name}}</label>   
            <input ng-if='text.content !== null' type="text" id='txt{{text.id}}' ng-model='text.content' />
            <input ng-if='text.content === null' type="text" id='txt{{text.id}}' ng-value='selectedRow[text.listfieldname]'   ng-keyup='manual(text, this)' />
            <span ng-if='text.listfieldname !== null'>
                <input type='checkbox' ng-init='text.uselist = (text.content === null)' ng-checked='text.content === null' ng-change='bindSelectList(text)' ng-model='text.uselist'/>
                <label>use select list</label>
            </span>
        </div>
    </div>
</div>

controller.js:

angular.module('myApp', [])
    .controller('myCtrl', function ($scope, $timeout) {
    $scope.selectionList = [
        {'id': 5, 'name': 'row 5', 'field1': 'row5field1', 'field2': 'row5field2' }, 
        {'id': 9, 'name': 'row 9', 'field1': 'row9field1', 'field2': 'row9field2' }];

    $scope.selectedRow = $scope.selectionList[1];

    $scope.texts = [{
        'id': 453,
            'name': 'Input Text1',
            'content': null,
            'listfieldname': 'field1'
    }, {
        'id': 455,
            'name': 'Input Text2',
            'content': 'manual entry',
            'listfieldname': 'field2'
    }];

    $scope.bindSelectList = function(text) {
        if (text.uselist) { //set value to get from select list
            //??.ngValue = 'selectedRow[text.listfieldname]'
        } else { //bind to text.content
            //??.ngModel = 'text.content'
        }

    };
    $scope.manual = function(text, txtInput) {
        text.uselist = false;   
        //??.ngModel = 'text.content'
        console.log(text);
    };
});

here's the jsfiddle for the above code

编辑:我想要小提琴做什么:

  • 用户单击“输入文本2”的“使用选择列表”,然后应将内容替换为“row9field2”(假设仍在ddl中选择了行ID 9)
  • 用户手动将数据输入“输入文本1”(或取消选中该输入的“使用选择列表”):这应该反映在$ scope.texts [0] .content的模型中。

0 个答案:

没有答案
相关问题