我试图检查字符串的长度,但它不起作用,有人可以帮我找到我做错的事吗?
HTML
<div ng-app="myApp" ng-controller="formCtrl">
<form novalidate> First Name:<br> <input type="text" ng-model="user.firstName"><br>
<button ng-click="check()">RESET</button>
</form> <p>form = {{user}}</p> </div>
JS是
var app = angular.module('myApp', []);
app.controller('formCtrl', function($scope) {
$scope.check = function() {
var arr = $scope.user;
if (arr.length<=3){
$scope.user="enjoy"
}
};
$scope.check();
});
答案 0 :(得分:0)
您尚未在控制器中声明$scope.user
并调用check()
功能。这样做会给你
TypeError: Cannot read property 'length' of undefined
因此您需要将$scope.user
声明为
$scope.user= {
firstName : ''
};
HTML
<div ng-app="myApp" ng-controller="formCtrl">
<form novalidate> First Name:<br> <input type="text" ng-model="user.firstName"><br>
<button ng-click="check()">RESET</button>
</form> <p>form = {{user}}</p> </div>
所以你的控制器就像这样
angular.module('myApp',[]).controller('formCtrl', function($scope){
$scope.user= {
firstName : ''
};
$scope.check = function() {
var arr = $scope.user.firstName;
if (arr.length<=3){
$scope.user.firstName="enjoy"
}
};
$scope.check();
})
为简单起见,这里的解决方法是指向JSFIDDLE
的链接