【问题标题】:angularjs with ng-repeat. cant access the data in controler when i use ng-repeat带有 ng-repeat 的 angularjs。当我使用 ng-repeat 时无法访问控制器中的数据
【发布时间】:2016-03-09 01:46:43
【问题描述】:

我将以下 ng-model 与 ng-repeat 一起使用,并尝试访问控制器中的数据,但似乎无法访问那里的数据。

<div ng-controller="myCtrl" class="container">
    <fieldset data-ng-repeat="contact in choices">
        <input class="form-control" ng-model='contact.firstname'>
        <input class="form-control" ng-model='contact.lastname'>
        <input class="form-control" ng-model='contact.email'>
        <input class="form-control" ng-model='contact.contact'>
        <input class="form-control" ng-model='contact.adress'>
        <input class="form-control" ng-model='contact.city'>
        <input class="form-control" ng-model='contact.state'>
        <button class="btn btn-primary" ng-click="addcontact()">Add</button></td>
    </fieldset>
    <button class="addfields" ng-click="addNewChoice()">Add fields</button>
    <div id="choicesDisplay">
        {{ choices }}
    </div>
</div>    
</div>    
</div>

并使用以下 ng-app

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
    $scope.choices = [{
        id: 'choice1'
    }];
    $scope.addNewChoice = function() {
        var newItemNo = $scope.choices.length + 1;
        $scope.choices.push({
            'id': 'choice' + newItemNo
        });
    };
    $scope.removeChoice = function() {
        var lastItem = $scope.choices.length - 1;
        $scope.choices.splice(lastItem);
    };
    var refresh = function() {
        $http.get('/contactlist').success(function(response) {
            console.log("in m new controler now");
            $scope.contactlist = response;
            $scope.contact = "";
        });
    };    
    refresh();
    $scope.addcontact = function() {
        console.log($scope.contact);
        $http.post('/contactlist', $scope.contact).success(function(response)
            {
                console.log(response);
                refresh();
            });
    };
});

我无法通过 ng-repeat 访问 $scope 中动态添加的控件的数据

【问题讨论】:

    标签: angularjs ng-repeat


    【解决方案1】:

    为了访问您应该使用的数据

       $scope.choices[index] 
    

    索引是你要访问的索引数

    【讨论】:

    • 但我是动态添加控件的,我怎么知道 index 的值是多少
    • 你必须在函数中建立索引,例如如果你想在 addcontact 函数中获取索引,它必须像 html 中的 addcontact(contact.$index)
    • 如果你想获得最新的,那么在控制器中你必须使用 var index= $scope.choices.length-1;然后使用 $scope.choices[index]
    猜你喜欢
    • 2013-08-11
    • 2017-12-22
    • 1970-01-01
    • 2016-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-18
    • 2013-11-23
    相关资源
    最近更新 更多