2017-10-10 53 views
0

我正在嘗試使用AngularJs做一件簡單的事情,但無法這樣做。我的要求 - 將會有一個TextBox,用戶應該輸入它。假設如下所示:當用戶開始輸入,並且當字長等於一個使用AngularJs計數名稱更改的發生

<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> 

onCount功能將正常工作。現在的問題是,用我下面的代碼,它計算雙:

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

雙重手段,想,我打字一個Text約翰,它計數1,當我刪除它,然後再次,它計數所以總數變成了2.它不應該計算被擦除的數字。我無法弄清楚我怎樣才能防止擦除的計數?以下是創建Employee對象下面的代碼,它使用工廠的功能:

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()]; 
    } 
]); 

回答

2

檢查名稱的長度等於零和減一:

employee.onCount = function() { 
    if(employee.employeeCount > 0 && employee.name.length==0){ 
     employee.employeeCount--; 
    } 
    else if (employee.name.length == 1) { 
     employee.employeeCount++; 
    } 
}; 
+0

完美工作@Hoyen。謝謝。 –