gpt4 book ai didi

AngularJS:如何在 AngularJS 中将数据从 View 传递到 Controller

转载 作者:行者123 更新时间:2023-12-02 22:42:32 26 4
gpt4 key购买 nike

我正在开发一个添加/编辑/删除联系人的应用程序。这是我的添加联系人 View 模板的样子:

<input placeholder="name" ng-model="contact.name" type="text">
<input placeholder="number" ng-model="contact.number" type="text">
<a href="#/"><button>Add</button></a>

这是我的 Controller 文件,用于添加的 Controller 是最后一个:

var myApp = angular.module('myApp', ['ngRoute']).config(function ($routeProvider) {
$routeProvider.when('/contact/:index', {
templateUrl: 'partials/edit.html',
controller: 'Edit'
}).when('/', {
templateUrl: 'partials/contacts.html'
}).when('/add', {
templateUrl: 'partials/add.html',
controller: 'Add'
})
.otherwise({ redirectTo: '/' });
}).controller('Contacts', ['$scope',function($scope){
$scope.contacts = [
{name:'Hazem', number:'01091703638'},
{name:'Taha', number:'01095036355'},
{name:'Adora', number:'01009852281'},
{name:'Esmail', number:'0109846328'}
];
}]).controller('Edit', ['$scope','$routeParams',function($scope,$routeParams){
$scope.contact = $scope.contacts[$routeParams.index];
$scope.index = $routeParams.index;
}]).controller('Add', ['$scope', function($scope){
$scope.contacts.push({name: contact.name, number: contact.number});
}]);

我在 chrome 检查器中遇到错误: ReferenceError:联系人姓名未定义

最佳答案

请看下面

使用<button ng-click="Add()">Add</button>代替<a>标签

var myApp = angular.module('myApp', [])
.controller('Add', ['$scope', function($scope){
$scope.contacts = [];
$scope.Add = function() {
$scope.contacts.push({name: $scope.contactname, number: $scope.contactnumber});
}
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="Add">
<input placeholder="name" ng-model="contactname" type="text">
<input placeholder="number" ng-model="contactnumber" type="text">
<button ng-click="Add()">Add</button>

<ul>
<li ng-repeat="con in contacts">{{con.name}} {{con.number}}</li>
</ul>

</div>
</div>
在您的添加 Controller 中改变

.controller('Add', ['$scope', function($scope){
$scope.contacts.push({name: contactname, number: contactnumber});
}]);

.controller('Add', ['$scope', function($scope){
$scope.contacts.push({name: $scope.contactname, number: $scope.contactnumber});
}]);

关于AngularJS:如何在 AngularJS 中将数据从 View 传递到 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26013535/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com