Я новичок в AngularJS, поэтому я пытаюсь учиться, создавая POC. Мое требование - simple-
Ниже приведен html code-
<body ng-app="myApp" class='container'>
<div ng-controller="Controller1 as ctrl">
<h1>Contacts Manager</h1>
<hr>
<div class="panel panel-primary">
<div class="panel-heading">Contact Editor</div>
<div class="panel-body">
<form role="form" >
<div class="form-group">
<label for="firstName">First Name</label>
<input type="text" name="firstName" class="form-control" placeholder="First Name" ng-model="contact.firstName"/>
</div>
<div class="form-group">
<label for="lastName">Last Name</label>
<input type="text" name="lastName" class="form-control" placeholder="Last Name" ng-model="contact.lastName"/>
</div>
<div class="form-group">
<label for="phoneNumber">Phone Number</label>
<input type="text" name="phoneNumber" class="form-control" placeholder="Phone Number" maxlength="10" ng-model="contact.phoneNumber"/>
</div>
</form>
</div>
<div class="panel-footer">
<input type="checkbox" name="disableAddRec" ng-model="disableAddRec"> <label for="disableAddRec">Disable Adding Contacts</label>
<span class="pull-right"><button name="addContact" class="btn btn-primary" ng-disabled="disableAddRec" ng-click="ctrl.addToContactList()">Add Contact</button></span>
</div>
</div>
<table class="table table-bordered table-hover" ng-if="ctrl.contactList.length > 0">
<thead>
<tr><th>S. No.</th><th>First Name</th><th>Last Name</th><th>Phone Number</th><th>Action</th></tr>
</thead>
<tbody>
<tr ng-repeat="cntct in ctrl.contactList">
<td>{{$index+1}}</td><td>{{cntct.firstName}}</td><td>{{cntct.lastName}}</td><td>{{cntct.phoneNumber}}</td>
<td><button class="btn btn-danger" ng-click="ctrl.removeContact($index)">Remove</button></td>
</tr>
</tbody>
</table>
</div>
</body>
Ниже приведен js code-
var myAppRef = angular.module("myApp", []);
myAppRef.controller("Controller1",['$scope', myController1]);
function myController1($scope) {
this.contactList = [];
this.addToContactList = function() {
this.contactList.push($scope.contact);
$scope.contact = {};
}
this.removeContact = function(idx) {
this.contactList.splice(idx,1); // contactList is undefined here... why?
}
}
Может кто-нибудь, пожалуйста, помогите мне определить, почему contactList не определено в removeContact?
Это неправильный контекст - ваше внутреннее this
не то же самое, как ваш внешний this
. Либо используйте $scope
либо сохраняйте ссылку на контекст контроллера.
Например:
var self = this;
self.contactList = [];
self.addToContactList = function() {
self.contactList.push($scope.contact);
$scope.contact = {};
}
this.removeContact = function(idx) {
self.contactList.splice(idx,1); // contactList is now defined
}
Или:
$scope.contactList = [];
$scope.addToContactList = function() {
$scope.contactList.push($scope.contact);
$scope.contact = {};
}
$scope.removeContact = function(idx) {
$scope.contactList.splice(idx,1); // contactList is now defined as well
}
Сделал небольшие изменения в вашем коде. Я сделал это без использования "Controller As"
<div ng-controller="Controller1">
<h1>Contacts Manager</h1>
<hr>
<div class="panel panel-primary">
<div class="panel-heading">Contact Editor</div>
<div class="panel-body">
<form role="form">
<div class="form-group">
<label for="firstName">First Name</label>
<input type="text" name="firstName" class="form-control" placeholder="First Name" ng-model="contact.firstName" />
</div>
<div class="form-group">
<label for="lastName">Last Name</label>
<input type="text" name="lastName" class="form-control" placeholder="Last Name" ng-model="contact.lastName" />
</div>
<div class="form-group">
<label for="phoneNumber">Phone Number</label>
<input type="text" name="phoneNumber" class="form-control" placeholder="Phone Number" maxlength="10" ng-model="contact.phoneNumber" />
</div>
</form>
</div>
<div class="panel-footer">
<input type="checkbox" name="disableAddRec" ng-model="disableAddRec">
<label for="disableAddRec">Disable Adding Contacts</label>
<span class="pull-right"><button name="addContact" class="btn btn-primary" ng-disabled="disableAddRec" ng-click="addToContactList()">Add Contact</button></span>
</div>
</div>
<table class="table table-bordered table-hover" ng-if="contactList.length > 0">
<thead>
<tr>
<th>S. No.</th>
<th>First Name</th>
<th>Last Name</th>
<th>Phone Number</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="cntct in contactList">
<td>{{$index+1}}</td>
<td>{{cntct.firstName}}</td>
<td>{{cntct.lastName}}</td>
<td>{{cntct.phoneNumber}}</td>
<td>
<button class="btn btn-danger" ng-click="removeContact($index)">Remove</button>
</td>
</tr>
</tbody>
</table>
</div>
Код JS:
var myAppRef = angular.module("myApp", []);
myAppRef.controller("Controller1", ['$scope', myController1]);
function myController1($scope) {
$scope.contactList = [];
$scope.addToContactList = function() {
$scope.contactList.push($scope.contact);
$scope.contact = {};
}
$scope.removeContact = function(idx) {
$scope.contactList.splice(idx, 1); // contactList is undefined here... why?
}
}
Пожалуйста, проверьте эту скрипку. https://jsfiddle.net/Ashyboy/vv8jt6sh/
Ваш точный код работает здесь! Попробуйте запустить его здесь.
var myAppRef = angular.module("myApp", []);
myAppRef.controller("Controller1",['$scope', myController1]);
function myController1($scope) {
this.contactList = [];
this.addToContactList = function() {
this.contactList.push($scope.contact);
$scope.contact = {};
}
this.removeContact = function(idx) {
this.contactList.splice(idx,1); // contactList is undefined here... why?
}
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp" class='container'>
<div ng-controller="Controller1 as ctrl">
<h1>Contacts Manager</h1>
<hr>
<div class="panel panel-primary">
<div class="panel-heading">Contact Editor</div>
<div class="panel-body">
<form role="form" >
<div class="form-group">
<label for="firstName">First Name</label>
<input type="text" name="firstName" class="form-control" placeholder="First Name" ng-model="contact.firstName"/>
</div>
<div class="form-group">
<label for="lastName">Last Name</label>
<input type="text" name="lastName" class="form-control" placeholder="Last Name" ng-model="contact.lastName"/>
</div>
<div class="form-group">
<label for="phoneNumber">Phone Number</label>
<input type="text" name="phoneNumber" class="form-control" placeholder="Phone Number" maxlength="10" ng-model="contact.phoneNumber"/>
</div>
</form>
</div>
<div class="panel-footer">
<input type="checkbox" name="disableAddRec" ng-model="disableAddRec"> <label for="disableAddRec">Disable Adding Contacts</label>
<span class="pull-right"><button name="addContact" class="btn btn-primary" ng-disabled="disableAddRec" ng-click="ctrl.addToContactList()">Add Contact</button></span>
</div>
</div>
<table class="table table-bordered table-hover" ng-if="ctrl.contactList.length > 0">
<thead>
<tr><th>S. No.</th><th>First Name</th><th>Last Name</th><th>Phone Number</th><th>Action</th></tr>
</thead>
<tbody>
<tr ng-repeat="cntct in ctrl.contactList">
<td>{{$index+1}}</td><td>{{cntct.firstName}}</td><td>{{cntct.lastName}}</td><td>{{cntct.phoneNumber}}</td>
<td><button class="btn btn-danger" ng-click="ctrl.removeContact($index)">Remove</button></td>
</tr>
</tbody>
</table>
</div>
</body>
this
не то, что вы ожидаете, что означает, что removeContact не вызывается в вашем экземпляреmyController1
, а в другом объектеctrl.contactList
в метод removeContact . Но почему это не работает без передачи, как addToContactList