【问题标题】:Angularjs: ng-model not displaying properlyAngularjs:ng-model 无法正确显示
【发布时间】:2016-07-05 05:32:27
【问题描述】:

我有父子控制器关系。这是基本功能的非工作模型。我相信任何比我更有能力的人都可以让它为 Plunker 或 Fiddle 模型工作。 (所以可能有问题:$scope.data.contactList = [{ID: 1, Email: "someemail@email.com"}, {ID: 2, Email: "antheremail@email.com" }];) 我尝试为 contactList 数组创建一些对象。

无论如何。我希望能够单击下面代码中第二个表中的链接来调用 EditShowContact。在我的实际应用中,这将显示一个隐藏的 div,它显然会显示联系人的更多属性,而不仅仅是电子邮件。

在我的实际程序中,表格的值已正确填写(即我的 ng-repeat 指令工作正常),但我似乎无法让 ng-model 指令响应。我尝试了各种不同的方法,但似乎没有任何效果。

<html ng-app="myApp"><head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script>
<script>

var app = angular.module('myApp', []);

app.controller('ContactsController', function ($scope)
{   
    this.currentContactID = null;
    this.EditShowContact = function(intContactID)
    {   
        this.currentContactID = intContactID;
        //this.currentContact = $scope.data.contactList[intContactID]; unclear why this assignment fails
    };
});

app.controller('ActionsController', function ($scope)
{   $scope.data = {}; 
    $scope.data.contactList = [{ID: 1, Email: "someemail@email.com"}, {ID: 2, Email: "anotheremail@email.com"}];    
});

</script>
</head>
<body ng-controller="ActionsController as ActCtrl">

<div ng-controller="ContactsController as ContactsCtrl">
    <table border = "1";>
        <tr><th>Email</a></th>
            <th>Name</th></tr>
    </table>
    <div >
        <table  ng-repeat="Contact in ContactsCtrl.data.contactList" border="1">
            <tr>
                <td><a href="" ng-click="ContactsCtrl.EditShowContact(Contact.ID)" style="padding-left: 5px;">{{Contact.Email}}</a></td>
                <td>{{Contact.Name}}</td>
            </tr>
        </table>
    </div>
    <div>
        <form>
            <input type="input" ng-model="ContactsCtrl.data.contactList[currentContactID].Email"></input>
        </form>
    </div>
</div>
</body>
</html>

【问题讨论】:

    标签: angularjs angularjs-scope angularjs-ng-model


    【解决方案1】:

    这里有很多错误,例如:

    ContactsCtrl 没有关于ContactList 的信息。您正在尝试使用 index 中的 ID 在数组中查找对象,使用 &lt;div&gt; 内的 &lt;table&gt; 元素等等..

    基本上,我将两个控制器的需求减少到一个,并创建了一个Working Demo

    【讨论】:

    • 没关系。在你的帮助下,我刚刚发现了我的巨大疏忽。在我的完整程序中,我使用 Contact.ID 来引用一个不存在的contactList 索引。在演示代码中恰好是 ID 与索引匹配的情况。这就解释了为什么我的任务失败了。
    猜你喜欢
    • 2014-04-23
    • 2018-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多