0

I am trying to do a simple things using AngularJs but unable to do so. My requirement - There will be a TextBox and user should type in it. Say as the following:

<body ng-controller="EmployeeController">
  <div ng-repeat="m in Employees">
    <input type="text" ng-model="m.name" ng-change="m.onCount()">
    <h2>Count the occurrence of name changing {{m.employeeCount}}.</h2>
  </div>
</body>

The onCount function will work when user starts typing and when the word length is equal to one. Now the issue is, using my below code, it counts double:

 employee.onCount = function () {
    if (employee.name.length == 1) {
       employee.employeeCount += 1;
    }
 };  

Double means, suppose, I am typing a Text say John, it counts 1 and when I erase it, then again, it counts 1. So total becomes 2. It shouldn't count the erased one. I am not able to figure out how can I prevent the counting for the erased one? Here is the below code for creating employee object and it's function using factory:

var module = angular.module('myApp', []);
module.factory('employeeService', function () {
        var createDefaultEmployee = function () {
            var employee = {
                name: "",
                employeeCount: 0
            };

            employee.onCount = function () {
                if (employee.name.length == 1) {
                    employee.employeeCount += 1;
                }
            };
            return employee;
        };

        return {
            createEmployee: function (name) {
                var employee = createDefaultEmployee();
                employee.name = name;
                return employee ;
            }
        };
    });

module.controller('EmployeeController', ['$scope', 'employeeService',
     function ($scope, employeeService) {
        $scope.Employees= [employeeService.createEmployee()];
     }
]);

1 Answer 1

2

Check for the length of the name is equal zero and subtract one:

employee.onCount = function () {
    if(employee.employeeCount > 0 && employee.name.length==0){
       employee.employeeCount--;
    }
    else if (employee.name.length == 1) {
       employee.employeeCount++;
    }
 };
Sign up to request clarification or add additional context in comments.

1 Comment

Worked perfectly @Hoyen. Thanks.

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.