【发布时间】:2014-03-12 21:48:58
【问题描述】:
我是 angularJS 的新手。我正在尝试为输入标签编写自定义指令。我想要一个自定义输入,如下图所示。
基本上,如果用户输入了无效值,它应该呈现标签名称、文本字段和一些验证消息。下面是我尝试过但没有按预期工作的代码。
var controller = angular.module('FundooDirectiveTutorial', [])
.controller('FundooCtrl', function ($scope)
{
$scope.validValues = ["ABC", "XYZ"];
$scope.inputField = "Hello World";
$scope.updateInput = function (input)
{
$scope.inputField = input;
};
$scope.isValid = function ()
{
for (var i = 0; i < $scope.validValues.length; i++) {
if ($scope.validValues[i].toLowerCase().indexOf($scope.inputField.toLowerCase()) == 0) {
return true;
}
}
return true;
};
});
controller.directive('fundooInput', function ()
{
return {
restrict:'E',
scope:{
labelName:"=",
inputValue:'=',
onInputChange:'&',
isValid : '&'
},
template:'<div><label>scope.labelName</label><input type="text" ng-model="inputValue" ng-change="updateValidity(inputValue)">' +
'<h6 ng-show="valid">Entered value is not correct</h6></div>',
link:function (scope, elem, attrs)
{
scope.updateValidity = function (newValue)
{
scope.inputValue=newValue;
scope.onInputChange(newValue);
scope.valid = scope.isValid();
};
}
}
});
HTML 文件是
<html ng-app="FundooDirectiveTutorial">
<head>
<title>Input Directive Demo</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script>
<script type="text/javascript" src="app/controllers/FundooCtrl.js"></script>
</head>
<body ng-controller="FundooCtrl">
input value is {{inputField}}<br/>
<fundoo-input labelName="Name" input-value="inputField" on-input-change="updateInput(inputField)" is-valid="isValid()"/>
Latest input value is {{inputField}}
</body>
</html>
有人可以帮忙解决什么问题吗?
【问题讨论】: