加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-17 08:52:46 所属栏目:安全 来源:网络整理
导读:我正在开发一个添加/编辑/删除联系人的应用程序. 以下是我添加联系人视图模板的方式: input placeholder="name" ng-model="contact.name" type="text"input placeholder="number" ng-model="contact.number" type="text"a href="#/"buttonAdd/button/a 这是
我正在开发一个添加/编辑/删除联系人的应用程序.
以下是我添加联系人视图模板的方式:
<input placeholder="name" ng-model="contact.name" type="text">
<input placeholder="number" ng-model="contact.number" type="text">
<a href="#/"><button>Add</button></a>

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

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','$routeParams',function($scope,$routeParams){
    $scope.contact = $scope.contacts[$routeParams.index];
    $scope.index = $routeParams.index;
}]).controller('Add',function($scope){
    $scope.contacts.push({name: contact.name,number: contact.number});
}]);

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

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

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

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

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

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

controller('Add',function(){
   var vm = this;
   vm.contacts = []; //you declare your array of contacts in the controllers scope
   //vm.contacts = getContactsFromDB(); //typically you'd be getting your initial list from a DB

   //As good practice,you should initialize the objects in your scope:
   vm.contactname = '';
   vm.contactnumber = '';

   vm.Add = function() {
     vm.contacts.push({name: vm.contactname,number: vm.contactnumber});
     //Also you could add the data to a database
     /*
       ContactService
       .AddNewContact(vm.contactname,vm.contactnumber)
       .then(function(){
              vm.contacts.push(
                  {name: vm.contactname,number: vm.contactnumber});
       });
     */

     //Finally you should reset the form variables
     vm.contactname = '';
     vm.contactnumber = '';
   }  


}]);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读