Pablo Francesca Pablo Francesca - 4 months ago 27
AngularJS Question

Angularjs: ng-model not displaying properly

I have a parent and child controller relationship. This is a non-working mockup of the basic functionality. I'm sure anyone more competent than me can get it working for a Plunker or Fiddle model. (So there is probably something wrong with: $scope.data.contactList = [{ID: 1, Email: "someemail@email.com"}, {ID: 2, Email: "anotheremail@email.com"}];) I tried creating some objects for the contactList array.

Anyway. I want to be able to click a link in the second table in the code below to invoke EditShowContact. In my actual app, this will show a hidden div and it will obviously display more properties of a contact than just the email.

In my actual program, the values of the table are filled out properly (i.e. my ng-repeat directive is working fine), but I cant seem to get the ng-model directive to respond. I've tried various different ways and nothing seems to work.

<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>

Answer

There are quite a few errors here such as :

ContactsCtrl has no information about the ContactList. You are trying to find object in array using ID in place in index using <table> element inside <div> and more..

Bascially, i have reduced the need of two controllers to one and made a Working Demo.

Comments