ng-select与懒惰人口

时间:2015-06-05 05:34:13

标签: angularjs

这是一个编辑表单,首先填充父记录,然后填充依赖选择列表,然后预期父记录中的值预先选择组合框。

html

<select ng-model="data.trackId" >
    <option ng-repeat="track in tracks" value="{{track.id}}">{{track.name}}</option>

拉出父记录后的

初始结果。

if(data) {
            this.$scope.data.id = data.id;
            this.$scope.data.name = data.name;
            this.$scope.data.room = data.room;
            this.$scope.data.start = data.start;
            this.$scope.data.end = data.end;
            this.$scope.data.dayId = data.day_id;
            this.$scope.data.trackId = data.track_id;
            this.$scope.data.color = data.color;
            this.$scope.data.description = data.description;
            this.$scope.$apply();
            this.$element[0].removeAttribute("style");
        }

//后来的跟踪结果被拉了

trackResult: function(data, status, headers, config) {
    for(var i=0; i<data.length; i++) {
        this.$scope.tracks.push(data[i]);
    }
    this.$scope.$apply();
},

问题:

列表从第二个调用trackResult填充,但$ scope.trackId的默认值从不将组合框设置为值。

编辑:控制器主体

controller: function($scope, $element) {
    var self = this;
    this.$scope = $scope;
    this.$element = $element;
    this.$scope.data = {};
    this.$scope.days = [];
    this.$scope.tracks = [];
    this.$scope.submit = function() {self.submit()};
    this.$scope.cancel = function() {self.cancel()};
},

1 个答案:

答案 0 :(得分:0)

编辑:更新了从示波器外部设置数据(OP请求)

使用ng-options&amp; ng-model

这就是我认为它应该在angularjs中完成的方式。 使用内置的数据绑定功能来简化代码并使其更简单

将列表绑定到<select>并控制所选项目,下面的代码段可以解决问题。

http://jsfiddle.net/72em40j4/

<强> JS

var myapp = angular.module('myapp', []);
myapp.controller('Ctrl', function ($scope) {
    $scope.options = [];
    $scope.selectedOption = null;
});

<强> HTML

<script>
    function clickFromOutside() {
        var controllerElement = document.getElementById('container');
        var controllerScope = angular.element(controllerElement).scope();


        var firstTrack = {
            id: 1,
            first: 'First',
            last: 'Track'
        };

        var secondTrack = {
            id: 2,
            first: 'Second',
            last: 'Track'
        };

        controllerScope.options.push(firstTrack);
        controllerScope.options.push(secondTrack);

        controllerScope.selectedOption = secondTrack;

        controllerScope.$apply();


    }
</script>

<button onclick="clickFromOutside();">outside</button>
<div ng-app="myapp">
    <fieldset id="container" ng-controller="Ctrl">
        <select ng-options="p.first + ' ' + p.last for p in options" ng-model="selectedOption"></select> <pre>{{ selectedOption }}</pre>

    </fieldset>
</div>