0

i have a problem with my model.

I need send a list of another object to my controller, but i dont know how to create this object using AngularJS. I have three input field, homePhone, cellphone and contact, all fields are about phone, and my ClientModel has a list of phones. What i want to do, is get this three fields and include in a list inside client model.

**MVC Model "Client"**

    public int Id { get; set; }
    public string Name { get; set; }
    public string Email{ get; set; }
    public IEnumerable<Phone> Phones { get; set; }

**MVC Model "Phone"**

    public int PhoneId { get; set; }
    public int ClientId { get; set; }
    public int PhoneType { get; set; }
    public string Number { get; set; }

View

<div class="form-group col-lg-4">
    <label>Home Phone</label>
    <input class="form-control" ng-model="?">
</div>

<div class="form-group col-lg-4">
    <label>Cellphone</label>
    <input class="form-control" ng-model="?">
</div>

<div class="form-group col-lg-4">
    <label>Contact Phone</label>
    <input class="form-control" ng-model="?">
</div>

<button class="btn btn-primary" style="float: right" ng-click="saveClient(client)">Confirmar</button>

Controller JS

    $scope.saveClient = function(client) {
            clientesAPI.saveCliente(client).success(function() {
                alert('OK');
            }).error(function () {
                alert('Error');
            });`enter code here`
        }
1

3 Answers 3

1

What you could do is create actual Constructor functions in JS and consistently model you current Server Side MVC Model.

So is would look something like this ...

angular.module('app', [])
  .factory('Client', function() {
    return Client;

    function Client() {
      this.id = 0;
      this.name = '';
      this.email = '';
      this.phones = [];
    }

    Client.prototype.init = function(client) {
      this.id = client.id;
      this.name = client.name;
      this.email = client.email;
      this.phones = [];
    }

  })
  .factory('Phone', function() {
    return Phone;

    function Phone() {
      this.phoneId = 0;
      this.clientId = 0;
      this.phoneType = 'Default Phone Type';
      this.number = 0;
    }

    Phone.prototype.init = function(phone) {
      this.phoneId = phone.phoneId;
      this.clientId = phone.clientId;
      this.phoneType = phone.phoneType;
      this.number = phone.number;
    }
  })
  .factory('clientService', function($http, $log, Client, Phone) {
    var service = {
      getClient: getClient,
      saveClient: saveClient
    };

    return service;

    //////////////////////////

    function getClient() {
      return $http.get('clientApi')
        .then(success)
        .catch(error)

      // This is where defining actual JS Quote unQuote Classes comes in handy
      function success(response) {
        var clients = response.data;
        angular.forEach(clients, function(client) {
          client = new Client().init(client);

          angular.forEach(client.phones, function(phone) {
            phone = new Phone().init(phone);
          })
        })

        return clients;
      }

      function error(response) {
        $log.error('Error getting Clients: ' + response.data);
      }
    }

    function saveClient(client) {

      return $http.post('clientApi', client)
        .then(success)
        .catch(error)

      // This is where defining actual JS Quote unQuote Classes comes in handy
      function success(response) {
        $log('Saved Client Successfully');
      }

      function error(response) {
        $log.error('Error saving Client: ' + response.data);
      }
    }
  })
  // I would use Controller As Syntax normally
  .controller('clientController', function($scope, clientService, Client, Phone) {
    $scope.client = new Client();
    $scope.client.phones.push(new Phone());
    $scope.savedClient;

    $scope.saveClient = function() {

      $scope.savedClient = $scope.client;
      alert('Yeah we saved some data!!');
      //Unconmment this to access the real service, Nowhere to call here :-)
      //clientService.saveClient($scope.client);
    };
  })
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
  <div ng-controller="clientController">
    <!-- Use ngRepeat to simplify things a bit -->
    <div class="form-group col-lg-4" ng-repeat="phone in client.phones track by phone.phoneId">
      <label>{{phone.phoneType}}</label>
      <input class="form-control" ng-model="phone.number">
    </div>

    <!-- You will already have access to the updated model in you controller -->
    <button class="btn btn-primary" style="float: right" ng-click="saveClient()">Confirmation</button>

    <!--Display Saved Data-->
    <pre>{{savedClient | json}}</pre>
  </div>
</div>

I like the idea of this approach for a couple of reasons.

  1. You can new up a Client or a Phone in you controller and know for a fact that or expected model properties are there when Angular tries to render them. (This avoids the annoying client.phones.phoneId is not defined errors)

  2. Your model definition is now in one spot on the JS side of the house. Even though this looks like duplication ... well it is, but you will have to define this somewhere to send it back to the server anyways. So I prefer to do it in one reusable spot.

  3. You get and Arrays of Client and Phone when you are outputting the model properties to the Console. This just make me feel good :-)


This was a bit of an overkill for your question, but I like the clean feel of this approach to Front End Modeling.

Sign up to request clarification or add additional context in comments.

1 Comment

Sorry for delay to respond
0

You can create a new object for your model and add the phones property there.

View

<div class="form-group col-lg-4">
    <label>Home Phone</label>
    <input class="form-control" ng-model="homePhone">
</div>

<div class="form-group col-lg-4">
    <label>Cellphone</label>
    <input class="form-control" ng-model="cellPhone">
</div>

<div class="form-group col-lg-4">
    <label>Contact Phone</label>
    <input class="form-control" ng-model="contactPhone">
</div>

<button class="btn btn-primary" style="float: right" ng-click="saveClient()">Confirmar</button>

Controller

$scope.saveClient = function() {
    var phones = [
       {ClientId: $scope.client.Id, PhoneType: 1, Number: $scope.homePhone},
       {ClientId: $scope.client.Id, PhoneType: 2, Number: $scope.cellPhone},
       {ClientId: $scope.client.Id, PhoneType: 3, Number: $scope.contactPhone}
    ]; // Not sure about the PhoneTypes. There are multiple ways to implement this, I'll leave it up to you.
    var data = {
       Id: $scope.client.Id,
       Name: $scope.client.Name,
       Email: $scope.client.Email,
       Phones: phones
    };    
    clientesAPI.saveCliente(data).success(function() {
        alert('OK');
    }).error(function () {
        alert('Error');
    });
};

Comments

0

first you need to define ng-model for your view, suppose -

<input class="form-control" ng-model="hPhone">
<input class="form-control" ng-model="cellPhone">
<input class="form-control" ng-model="contactPhone">

Now you can make a json object and post that, then on server side you can access all the phones by for-each loop -inside your controller -

var vm = this;
var phnList = {
  hphone: vm.hphone,
  cellPhone: vm.cellPhone,
  contactPhn: vm.contactPhone
};

Now u can post using $http service

$(http).({
  url : "urULR",
  data : phnList,
  method :"post"
}).then(fuction(response) {
  vm.message = "save success";
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.