如何使用angularjs添加数据

时间:2015-01-09 10:23:56

标签: javascript angularjs

我是angularjs的新手。我想在数据库中添加数据并在表格中显示。有一个输入名称字段和一个图像字段。

我的HTML是 service.html

  <div aria-hidden="true" aria-labelledby="myModalLabel" role="dialog" tabindex="-1" id="addservices" class="modal fade">
                <form role="form" name="myForm" ng-submit="submitCuisine(myForm.$valid)" novalidate>
      <div class="modal-dialog" >
          <div class="modal-content">
              <div class="modal-header">

                  <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                  <h4 class="modal-title">Add Service</h4>
              </div>
              <div class="modal-body" ng-class="{ 'has-error' : myForm.cat.$invalid && myForm.cat.$touched }">

                  Category <input type="text" name= "cat" id= "cat" ng-model="dataform.cat"  autocomplete="off" class="form-control placeholder-no-fix">
              </div><br>
             <div class="modal-body" ng-class="{ 'has-error' : myForm.name.$invalid && myForm.name.$touched }"> Service Name<input type="text" name= "name" id= "name" ng-model="dataform.name"  autocomplete="off" class="form-control placeholder-no-fix"></div>
                 <div class="modal-body" ng-class="{ 'has-error' : myForm.desc.$invalid && myForm.desc.$touched }"> Description<input type="text" name= "desc" id= "desc" ng-model="dataform.desc" autocomplete="off" class="form-control placeholder-no-fix"></div>
                <div class="modal-body" ng-class="{ 'has-error' : myForm.cost.$invalid && myForm.cost.$touched }">  Cost($)<input type="text" name= "cost" id= "cost"  ng-model="dataform.cost" autocomplete="off" class="form-control placeholder-no-fix"></div>
                <div class="modal-body" ng-class="{ 'has-error' : myForm.servicetime.$invalid && myForm.servicetime.$touched }">  Time(min)<input type="text" name= "servicetime" id= "servicetime" ng-model="dataform.servicetime"  autocomplete="off" class="form-control placeholder-no-fix"></div>
                <div class="modal-body">  Image  <input type="file"  file-input="files" name="file"/>
              </div>
              <div class="modal-footer">
                  <button data-dismiss="modal" class="btn btn-default" type="button">Cancel</button>
                  <button class="btn btn-success" type="submit" ng-disabled="myForm.$invalid">Submit</button>
              </div>
          </div>
      </div>
                </form>
  </div>

addserviceController.js

 app.controller('addserviceController', function ($scope,$http,$cookieStore) {


       $scope.submitCuisine=function(isvalid){
        if(isvalid){
            var fd=new FormData();
            angular.forEach($scope.files,function(file){
                fd.append('file',file);
            });

            fd.append('formdata',JSON.stringify($scope.dataform));

            $http.post('admin/managecuisineAdd',fd,{
                access_token : $cookieStore.get('obj').accesstoken,
                transformRequest:angular.identity,
                headers:{'Content-type':undefined}
            }).success(function(data){
                $scope.status=data;
                $scope.itemlist.push(data)
                $scope.message="New Dish Added Successfully"
            });
        }   
    } 



});

app.js

(function(window){

var app= angular.module('customersApp',['ngRoute','ngCookies','ui.bootstrap']);




app.directive("fileInput",['$parse',function($parse){
    return{
        restrict:'A',
        link:function(scope,ele,attrs){
            ele.bind('change',function(){
                $parse(attrs.fileInput).
                assign(scope,ele[0].files)
                scope.$apply()
            });
        }
    }
}]);
app.config(['$routeProvider',
  function ($routeProvider) {
        $routeProvider.
        when('/login', {
            title: 'Login',
            controller: 'loginController',
               templateUrl: 'app/views/loginuser.html'
        })

            .when('/logout', {
                title: 'Logout',
                templateUrl: 'partials/login.html',
                controller: 'loginController'
            })

            .when('/dashboard', {
                title: 'Dashboard',
                templateUrl: 'app/views/dynamic_table.html',
                controller: 'dashboard'
            })
            .when('/verified_artists', {
                title: 'Verified Artists',
                templateUrl: 'app/views/verified_artists.html',
                controller: 'artistController'
            })
            .when('/new_artists', {
                title: 'New Request Artists',
                templateUrl: 'app/views/new_artists.html',
                controller: 'verifyartistController'
            })
            .when('/services', {
                title: 'Services',
                templateUrl: 'app/views/services.html',
                controller: 'serviceController'
            })
           .when('/addservices', {
                title: 'Services',
                templateUrl: 'app/views/services.html',
                controller: 'addserviceController'
            })

  }]);
   window.app = app;

}(window));

我制作了一个控制器addserviceController.js。我希望当我点击“提交”按钮时,它会转到控制器,我会点击api,但我不知道如何发送名称和图像字段的数据,也帮助我在控制器中写的内容。请告诉我如何获取输入字段的数据并传递给控制器​​,在那里它将命中一个api,以便数据保存到数据库。

3 个答案:

答案 0 :(得分:0)

您应该使用$ http服务来发出AJAX请求或与RESTful服务进行交互。 有关如何使用$ http服务的详细信息是here

答案 1 :(得分:0)

Here is the code what i did in my project to upload image and data:- 
HTML PAGE :-
<form role="form" name="myForm" ng-submit="submitCuisine(myForm.$valid)" novalidate>
            <div class="form-group" ng-class="{ 'has-error' : myForm.name.$invalid && myForm.name.$touched }">
               <label for="name">Name</label>
               <input type="text" class="form-control" id="name"  name="name"
                  placeholder="Name of cuisine" ng-model="dataform.name" required>
            </div>
            <div class="form-group" ng-class="{ 'has-error' : myForm.description.$invalid && myForm.description.$touched }">
               <label for="description">Description</label>
               <input type="text" class="form-control" id="description" name="description" 
                  placeholder="Description for cuisine" ng-model="dataform.description" required>
            </div>
            <div class="form-group" ng-class="{ 'has-error' : myForm.category.$invalid && myForm.category.$touched }">
               <label for="description">Category</label>
                <select class="form-control" ng-model="dataform.category" id="category" name="category" required>
                   <option>Veg</option>
                   <option>Non-veg</option>
                 </select>
            </div>
            <div class="form-group" ng-class="{ 'has-error' : myForm.subcategory.$invalid && myForm.subcategory.$touched }">
               <label for="description">Sub-Category</label>
                <select class="form-control" ng-model="dataform.subcategory" id="subcategory" name="subcategory" required>
                   <option>Main Course</option>
                   <option>Staters</option>
                 </select>
            </div>
            <div class="form-group" ng-class="{ 'has-error' : myForm.price.$invalid && myForm.price.$touched }">
               <label for="description">Price</label>
               <span class="fa fa-dollar"></span>
               <input type="number" class="form-control" id="price" name="price" 
                  placeholder="Price" ng-model="dataform.price" required>
            </div>  
            <div class="form-group">
               <label for="description">Image</label> 
               <input type="file"  file-input="files" name="file"/>
            </div>  
            <button class="btn btn-primary" type="submit" ng-disabled="myForm.$invalid"> Submit</button>
        </form>



Controller:-
$scope.submitCuisine=function(isvalid){
    if(isvalid){
        var fd=new FormData();
        angular.forEach($scope.files,function(file){
            fd.append('file',file);
        });

        fd.append('formdata',JSON.stringify($scope.dataform));

        $http.post('admin/managecuisineAdd',fd,{
            transformRequest:angular.identity,
            headers:{'Content-type':undefined}
        }).success(function(data){
            $scope.status=data;
            $scope.itemlist.push(data)
            $scope.message="New Dish Added Successfully"
        });
    }   
}

Directive :-
myApp.directive("fileInput",['$parse',function($parse){
    return{
        restrict:'A',
        link:function(scope,ele,attrs){
            ele.bind('change',function(){
                $parse(attrs.fileInput).
                assign(scope,ele[0].files)
                scope.$apply()
            });
        }
    }
}]);

答案 2 :(得分:0)

好的,我以为你可以使用angular-ui和来自bootstrap的模态。

此示例是根据您的需要修改http://angular-ui.github.io/bootstrap/的示例。

<!doctype html>
<html ng-app="ui.bootstrap.demo">

<head>
  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.js"></script>
  <script src="//angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.12.0.js"></script>
  <script src="example.js"></script>
  <link href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet">
</head>

<body>

  <div ng-controller="ModalDemoCtrl">
    <script type="text/ng-template" id="myModalContent.html">
      < div class = "modal-header" > < h3 class = "modal-title" > I 'm a modal!</h3>
        </div>
        <div class="modal-body">
        <label>Your Variable
        <input ng-model="variable" />
        </label>
            <p>Variable: <b>{{ variable }}</b></p>
        </div>
        <div class="modal-footer">
            <button class="btn btn-primary" ng-click="ok()">OK</button>
            <button class="btn btn-warning" ng-click="cancel()">Cancel</button>
        </div>
    </script>

    <button class="btn btn-default" ng-click="open()">Open me!</button>
    <button class="btn btn-default" ng-click="open('lg')">Large modal</button>
    <button class="btn btn-default" ng-click="open('sm')">Small modal</button>
    <div ng-show="variable">Variable input from a modal: {{ variable }}</div>
  </div>
</body>

</html>

和你的javascript:

angular.module('ui.bootstrap.demo', ['ui.bootstrap']);
angular.module('ui.bootstrap.demo').controller('ModalDemoCtrl', function($scope, $modal, $log) {

  $scope.variable = "initial value";

  $scope.open = function(size) {

    var modalInstance = $modal.open({
      templateUrl: 'myModalContent.html',
      controller: 'ModalInstanceCtrl',
      size: size,
      resolve: {
         variable: function() {
           return $scope.variable;
         }
      }
    });

    modalInstance.result.then(function(variable) {

      //your special processing here
      $scope.variable = variable.toUpperCase();
    }, function() {
      $log.info('Modal dismissed at: ' + new Date());
    });
  };
});

// Please note that $modalInstance represents a modal window (instance) dependency.
// It is not the same as the $modal service used above.

angular.module('ui.bootstrap.demo').controller('ModalInstanceCtrl', function($scope, $modalInstance, variable) {

  $scope.variable = variable;

  $scope.ok = function() {
    $modalInstance.close($scope.variable);
  };

  $scope.cancel = function() {
    $modalInstance.dismiss('cancel');
  };
});

我在这里做同样的事情,一切正常。

工作演示:

http://plnkr.co/edit/yXEGPXejWdlLrniDGQs5?p=preview