AngularJS:如何在angularjs中将数据从视图传递到控制器

前端之家收集整理的这篇文章主要介绍了AngularJS:如何在angularjs中将数据从视图传递到控制器前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在开发一个添加/编辑/删除联系人的应用程序.
以下是我添加联系人视图模板的方式:
  1. <input placeholder="name" ng-model="contact.name" type="text">
  2. <input placeholder="number" ng-model="contact.number" type="text">
  3. <a href="#/"><button>Add</button></a>

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

  1. var myApp = angular.module('myApp',['ngRoute']).config(function ($routeProvider) {
  2. $routeProvider.when('/contact/:index',{
  3. templateUrl: 'partials/edit.html',controller: 'Edit'
  4. }).when('/',{
  5. templateUrl: 'partials/contacts.html'
  6. }).when('/add',{
  7. templateUrl: 'partials/add.html',controller: 'Add'
  8. })
  9. .otherwise({ redirectTo: '/' });
  10. }).controller('Contacts',['$scope',function($scope){
  11. $scope.contacts = [
  12. {name:'Hazem',number:'01091703638'},{name:'Taha',number:'01095036355'},{name:'Adora',number:'01009852281'},{name:'Esmail',number:'0109846328'}
  13. ];
  14. }]).controller('Edit','$routeParams',function($scope,$routeParams){
  15. $scope.contact = $scope.contacts[$routeParams.index];
  16. $scope.index = $routeParams.index;
  17. }]).controller('Add',function($scope){
  18. $scope.contacts.push({name: contact.name,number: contact.number});
  19. }]);

我在chrome检查员中遇到错误说:
ReferenceError:未定义contactname

  1. controller('Add',function(){
  2. this.contacts.push({name: contactname,number: contactnumber});
  3. }]);

每个控制器都有自己的范围,在Add控制器中,您只是尝试将未定义的内容推送到也未定义$scope.contacts的变量中.

另外在您的视图中,当您将某些内容传递给ng-model时,这基本上是在控制器中具有该名称的变量之间创建双向数据绑定.所以在这种情况下,你的html将创建两个变量:$scope.contactname和$scope.contactnumber.

在您的视图中,您还调用了一个函数Add(),该函数尚未在您的控制器上定义.

以下是您的控制器应该是什么样子:

  1. controller('Add',function(){
  2. var vm = this;
  3. vm.contacts = []; //you declare your array of contacts in the controllers scope
  4. //vm.contacts = getContactsFromDB(); //typically you'd be getting your initial list from a DB
  5.  
  6. //As good practice,you should initialize the objects in your scope:
  7. vm.contactname = '';
  8. vm.contactnumber = '';
  9.  
  10. vm.Add = function() {
  11. vm.contacts.push({name: vm.contactname,number: vm.contactnumber});
  12. //Also you could add the data to a database
  13. /*
  14. ContactService
  15. .AddNewContact(vm.contactname,vm.contactnumber)
  16. .then(function(){
  17. vm.contacts.push(
  18. {name: vm.contactname,number: vm.contactnumber});
  19. });
  20. */
  21.  
  22. //Finally you should reset the form variables
  23. vm.contactname = '';
  24. vm.contactnumber = '';
  25. }
  26.  
  27.  
  28. }]);

猜你在找的Angularjs相关文章