0
其他輸入設置有效期,我不是很熟悉,在AngularJS的指示,因爲我在依靠控制器使用。是否可以通過指令設置其他輸入的有效性?這是這種情況,我有一個按鈕,當它被點擊時。它應該對某個輸入文本設置一個有效性。但我似乎無法得到將設置有效性的代碼。使用時按一下按鈕指令在AngularJS
下面是HTML代碼:
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
</head>
<body>
<div class="container">
<div id="login-container">
<div class="form-group">
<span class="glyphicon glyphicon-user"></span>
</div>
<form name="loginForm" novalidate>
<div class="form-group">
dasdas -- {{ loginForm.student_code.$error.codeValidity }}
<input type="text" class="form-control text-center" name="student_code" ng-model="studentCode" placeholder="Enter Exam Code" required />
<span class="errors" id="error-student-code" ng-if="loginForm.student_code.$error.codeValidity">{{ errors }}</span>
</div>
</form>
<login-button form="loginForm"></login-button>
<a href="register"><button class="btn btn-primary">Register</button></a>
</div>
</div>
</body>
</html>
這裏是JS代碼:
var app = angular.module("myApp", []);
app.directive('loginButton', loginButton);
loginButton.$inject = ["$http", "$window"];
function loginButton($http, $window){
return {
template: '<button type="button" class="btn btn-primary">Take Exam</button>',
link: function(scope, element, attrs, ctrl){
element.on('click', function(){
form = attrs.form;
form.student_code.$setValidity('codeValidity', true);
scope.errors = "Code is Invalid";
});
}
}
}
這裏是關於plunker樣品:http://plnkr.co/edit/kcdDgZpStQixTpGWqxOp?p=preview
PS。
我知道這是可以使用的控制器可以輕鬆實現,但我想實現這個使用指令作爲我的實踐中去適應它。
你的回答是偉大的!但是,我錯過了一些東西。我有點改變了代碼。請看 {{errors}}。由於指令中聲明的「範圍:{}」數組,因此我無法爲指令的外部聲明任何範圍變量,如{{errors}}。如果codeValidity錯誤爲true,則應顯示錯誤消息 –
請提供jsfiddle,註釋無法讀取 – sielakos
請參閱http://plnkr.co/edit/kcdDgZpStQixTpGWqxOp?p=preview –