Javascript 类型错误:无法读取未定义的属性“拆分”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35144841/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
TypeError: Cannot read property 'split' of undefined
提问by Abhishek
This is my HTML file. When i am running the HTML page it is showing error,'Cannot read property 'split' of undefined'
这是我的 HTML 文件。当我运行 HTML 页面时,它显示错误,“无法读取未定义的属性 'split'”
<!DOCTYPE html>
<html>
<head>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.3/angular.min.js"></script>
<script>
var appModule=angular.module('appModule',[]);
appModule.filter('removeDashes',function(){
return function(text){
if(text!==undefined){
return text.split('-').join(' ');
}
}
});
appModule.controller('someCTRL',function($scope){
});
</script>
</head>
<body ng-app="appModule" ng-controller="someCTRL">
<input type="text" model="someDashedText">
<p>
{{someDashedText | removeDashes}}
</p>
</body>
</html>
回答by Nitin Garg
if(text!==undefined){
return text.split('-').join(' ');
}
In my opinion above condition should be replaced with below code
在我看来,上述条件应替换为以下代码
if(text){
return text.split('-').join(' ');
}
This condition checks all i.e defined, not null and not empty string.
这个条件检查所有即定义的、非空的和非空的字符串。
Hope this helps.
希望这可以帮助。
回答by oKonyk
You are missing ng
in <input type="text" model="someDashedText">
=> <input type="text" ng-model="someDashedText">
.
你ng
在<input type="text" model="someDashedText">
=>中不见了<input type="text" ng-model="someDashedText">
。
Not sure that 'strict not equal' !==
operator is necessary here..., you might just check if anything is there if(text)
不确定!==
此处是否需要“严格不等于”运算符...,您可以检查是否有任何内容if(text)
Here is working Plunker.
这是工作的Plunker。
回答by Siva
I have made a small code change and created a separate module for the filter and used in the 'appModule'.
我做了一个小的代码更改并为过滤器创建了一个单独的模块并在“appModule”中使用。
You must use "ng-model" in the input.
您必须在输入中使用“ng-model”。
Here is the working script.
这是工作脚本。
<!DOCTYPE html>
<html>
<head>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.3/angular.min.js"></script>
<script>
angular.module('dash',[]).filter('removeDashes',function(){
return function(text){
if(text!==undefined){
return text.split('-').join(' ');
}
}
});
angular.module('appModule', ['dash']).controller('someCTRL', function($scope){
});
</script>
</head>
<body ng-app="appModule" ng-controller="someCTRL">
<input type="text" ng-model="someDashedText">
<p>
{{someDashedText|removeDashes}}
</p>
</body>
</html>