无法读取属性'加入'为空
我是AngularJS的新手,我没有看到我的代码出了什么问题。尝试了很多变化,但每次我都会得到错误的结果。无法读取属性'加入'为空
<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
<title>acronyms</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://fonts.googleapis.com/css?family=Fredericka the Great">
</head>
<body>
<div class="container-fluid col-sm-4">
<h1>Something</h1>
<form role="form">
<div class="form-group">
<input name="userInput" id="userInput" class="form-control input-normal" placeholder="Enter Text Here" ng-model="userInput">
<br>
</div>
<div>The acronym for "{{userInput}}" is <span main-directive id="result" ng-bind="acronymOutput"></span></div>
</form>
</div>
<script>
var myApp = angular.module("myApp", []);
myApp.directive("mainDirective", function(){
var inputValue = document.getElementById("userInput").value;
var matches = inputValue.match(/\b(\w)/g);
var acronymOutput = matches.join("").toUpperCase();
document.getElementById("result").innerHTML = acronymOutput;
document.getElementById("userInput").value = ("");
return {
template: ("<h1>" + acronymOutput + "</h1>")
};
})
绑定的输入响应模型,通过这个模型到你的指令并处理它从那里
您可以使用'require'属性将模型传递给指令 –
请在与reg匹配后检查var matches
。 EXPR。
var matches = inputValue.match(/\b(\w)/g);
console.log(matches); // check in console
var mnemonicOutput="";
if(typeof matches == "array")
{
mnemonicOutput = matches.join("").toUpperCase();
}
根本没有帮助。我想让应用程序工作,而不是知道我的错误在哪里。我已经知道错误在哪里,因为它指出它是空的。 @Haresh Vidja –
可以这样写。
Array.isArray(matches) && matches.join("").toUpperCase();
OR
Object.prototype.toString.call(someVar) === '[object Array]' && matches.join("").toUpperCase();
你想使用正则表达式来创建一个缩写? 如果是这样,我认为最好是按“”分割然后加入。 替换这两行:
var matches = inputValue.match(/\b(\w)/g);
var mnemonicOutput = matches.join("").toUpperCase();
有了这个:
var matches = inputValue. split(' ').map(function(item){return item[0]}).join('');
var mnemonicOutput = matches.toUpperCase();
你做第一个错误是使用一个directive
当你需要触发的输入值的控制功能。 只需传递ng-model
中的值,处理它并将其还原。
var myApp = angular.module("myApp", []);
myApp.controller("AcronymController", function($scope) {
var vm = this;
vm.getAcronym = function() {
var matches = vm.userInput.match(/\b(\w)/g);
vm.acronymOutput = matches.join("").toUpperCase();
document.getElementById("userInput").value = ("");
};
});
这里是一个工作的jsfiddle: https://jsfiddle.net/9zL5nj8e/1/
呀,你没有正确创建指令。 Angular JS文档有关于指令的大量信息... –
阅读文档,学习指令,修复代码。 –