我在Angular JS 1.2.6应用程序的视图中嵌入了一个表单。
<div class="container" ng-controller="LoginCtrl as signin">
<div class="row">
<div class="col-md-4">
<form name="signin.myForm" novalidate autocomplete="off">
<h1>Sign In</h1>
<div class="form-group" ng-class="{'has-error': (signin.myForm.name.$error.required || signin.myForm.name.$error.minlength) && signin.myForm.name.$dirty}">
<label>Name</label>
<input class="form-control" type="text" name="name" ng-model="signin.myForm.data.name" required ng-minlength="3">
<span class="help-block" ng-show="signin.myForm.name.$error.required && signin.myForm.name.$dirty" >Name is required.</span>
<span class="help-block" ng-show="signin.myForm.name.$error.minlength && signin.myForm.name.$dirty" >Must be at least 3 characters.</span>
</div>
<button class="btn btn-primary" ng-disabled="!signin.myForm.$valid" ng-click="signin.submit()">Sign in</button>
</form>
</div>
控制器为:
app.controller('LoginCtrl', ['$log',function($log){
var ctrl = this;
ctrl.submit = function(){
console.log(ctrl.myForm);
if(ctrl.myForm.$valid){
console.log('the form is valid');
}
};
}]);
正如你所看到的,为了让表单字段的数据与我所教导的第一次ng-controller="LoginCtrl as signin"
的注册范围相同,然后我最终得到模型和属性的复杂名称,如{{ 1}}
这是正确的方法吗?它似乎工作,但虽然我是一个菜鸟,这似乎有点纠结我。这真的是最好的做法吗?
答案 0 :(得分:0)
我认为更常见的是看到类似这样的东西,你把东西附加到注入的$scope
而不是this
,然后你不必在引用中放置名称空间限定符HTML。
<div class="container" ng-controller="LoginCtrl">
<div class="row">
<div class="col-md-4">
<form name="myForm" novalidate autocomplete="off">
<h1>Sign In</h1>
<div class="form-group" ng-class="{'has-error': (myForm.name.$error.required || myForm.name.$error.minlength) && myForm.name.$dirty}">
<label>Name</label>
<input class="form-control" type="text" name="name" ng-model="signin.myForm.data.name" required ng-minlength="3">
<span class="help-block" ng-show="signin.myForm.name.$error.required && myForm.name.$dirty" >Name is required.</span>
<span class="help-block" ng-show="myForm.name.$error.minlength && myForm.name.$dirty" >Must be at least 3 characters.</span>
</div>
<button class="btn btn-primary" ng-disabled="!myForm.$valid" ng-click="submit()">Sign in</button>
</form>
</div>
app.controller('LoginCtrl', ['$scope', '$log',function($scope, $log){
$scope.submit = function(){
console.log($scope.myForm);
if($scope.myForm.$valid){
console.log('the form is valid');
}
};
}]);