我正在处理这个简单的客户表信息,例如:姓名,姓氏和年龄。我创建了一个函数,该函数允许用户添加新客户,并且效果很好:)。我还创建了一个弹出窗口,我想从弹出窗口添加新客户。我的弹出窗口可以正常工作,但是无法从中添加新客户。请帮我。非常感谢!!。
这是我的代码,可以正常运行
<script type="text/javascript">
var App = angular.module('sortApp', ['ui.bootstrap'])
App.controller('mainController', function($scope, $modal, $log, $filter) {
$scope.sortType = 'id'; // set the default sort type
$scope.sortReverse = false; // set the default sort order
$scope.searchPerson = ''; // set the default search/filter term
// Array - List of People
$scope.People = [
{ id: 1, name: 'Mike', Lastname: 'White', age: 26 },
{ id: 2, name: 'Carl', Lastname: 'Barns', age: 41 },
{ id: 3, name: 'Deb', Lastname: 'McDonals',age: 78 },
{ id: 4, name: 'Tommy', Lastname: 'Humbs', age: 32 }
];
/*
This function adds a new customer
*/
$scope.addPerson = function(){
var customer = {
name: $scope.name,
Lastname: $scope.Lastname,
age: $scope.age,
};
$scope.People.push(customer);
};
/*
This function removes a customer
*/
$scope.removePerson = function(index){
$scope.People.splice(index, 1);
};
$scope.openPopupScreen = function() {
var modalInstance = $modal.open({
template: '<div class="modal-header"> <a class="close" data- dismiss="modal" ng-click="cancel()">X</a><h1>Add Customer</h1></div><div class="modal-body"> <form >' +
' <label>Name:</label><input type="text" class="span3" ng-model="name"></br>' +
' <label>Lastname:</label><input type="text" class="span3" ng-model="Lastname"></br>' +
' <label>Age:</label><input type="number" class="span3" ng-model="age"></br>' +
' <button type="submit" class="btn btn-success" ng-click="addPerson()">Add In List</button>' +
' <button type="reset" class="btn ">Clear</button>' +
' </form>' +
'</div>' +
'<div class="modal-footer">' +
' <a data-dismiss="modal" aria-hidden="true" class="btn btn-primary" ng-click="cancel()">close</a>' +
'</div>',
controller: ModalInstanceCtrl
});
};
var ModalInstanceCtrl = function($scope, $modalInstance) {
$scope.ok = function() {
$modalInstance.close($scope.selected.item);
};
$scope.cancel = function() {
$modalInstance.dismiss('cancel');
};
};
});
</script>
最佳答案
在模态中,您调用addPerson(),但是该函数在mainController中,而不是模态控制器中,因此它无法正常工作
您需要提供一个函数来获取模态结果并将其传递回主控制器,例如在ModalInstanceCtrl中:
$scope.newPerson = {
//Bind ng-model from modal input to properties of this
};
$scope.add = function() {
//Pass newPerson to caller from main controller
$modalInstance.close($scope.newPerson);
};
记住将add()绑定到按钮单击上:
<button type="button" class="btn btn-success" ng-click="add()">Add In List</button>
在主控制器中:
var modalInstance = $modal.open({
//create modal
});
modalInstance.result.then(function (newPerson) {
$scope.addPerson(newPerson);
}, function () {
//User clicks dismiss instead of add
});