0

I am stuck on a problem. I want to take first and last names as Input show them as full names and add them separately on a table by push method. Full name function is working properly but another controller is either not working or showing the results.

 <!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.8.3/angular.min.js"
    integrity="sha512-KZmyTq3PLx9EZl0RHShHQuXtrvdJ+m35tuOiwlcZfs/rE7NZv29ygNA8SFCkMXTnYZQK2OX0Gm2qKGfvWEtRXA=="
    crossorigin="anonymous" referrerpolicy="no-referrer"></script>
</head>

<body>
  <div ng-app="myApp" ng-controller="myCtrl">
    <form name="myForm" ng-submit="addRow()">
      First Name: <input type="text" name="fname" ng-model="firstName"><br>
      Last Name: <input type="text" name="lname" ng-model="lastName"><br>
      <input type="submit" value="Submit"><br>
    </form>
    <p> Full Name: {{fullName()}}</p>
    <div ng-controller="tableCtrl">
      <table>
        <tr>
          <th>First Name</th>
          <th>Last Name</th>
        </tr>
        <tr ng-repeat="x in records">
          <td>{{x.firstName}}</td>
          <td>{{x.lastName}}</td>
        </tr>
      </table>
    </div>
  </div>
  <script>
    var app = angular.module('myApp', []);
    app.controller('myCtrl', function ($scope) {
      $scope.firstName = myForm.fname.value;
      $scope.lastName = myForm.lname.value;
      $scope.fullName = function () {
        return $scope.firstName + " " + $scope.lastName;
      };
    });
    app.controller('tableCtrl', ['$scope', function ($scope) {
      $scope.records = [];
      $scope.addRow = function () {
        $scope.records.push({
          'firstName': $scope.firstName,
          'lastName': $scope.lastName
        });
      };
    }]);
  </script>
</body>

</html>

This is the code of the index.html file I am using Angular js with a CDN link.

2
  • addRow function is used outside the tableCtrl - so is unknown. Put addRow function and list of records into myCtrl, to make it work. Then you do not need tableCtrl, exept if you want to add additional logic (delete row). Commented Oct 17, 2022 at 5:56
  • @AvgustinTomsic It worked, thank you. but it was not showing the full name so I had to define the full name function in the tableCtrl controller instead. Thank you! Commented Oct 19, 2022 at 16:41

0

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.