當我單擊「檢查」按鈕時,以下代碼將引發錯誤「TypeError:Can not read property'$ pristine'of undefined」。
app.controller('MainCtrl', function($scope) {
// other stuff
})
.controller('Ctrl2', function($scope) {
$scope.product = {description:'pump'};
$scope.output = 'unknown';
// uncomment to avoid undefined error, still can't see $pristine
// $scope.formHolder = {};
$scope.checkForm = function() {
$scope.descriptionTest = $scope.product.description;
if ($scope.formHolder.productForm.$pristine) {
$scope.output = 'yes';
}
if ($scope.formHolder.productForm.$dirty) {
$scope.output = 'no'
}
}
});
HTML
<body ng-controller="MainCtrl">
<div >
<ng-include ng-controller="Ctrl2" src="'myForm.html'"></ng-include>
</div>
</body>
myForm.html
<form name="productForm" novalidate>
<h2>myForm</h2>
description: <input type="text" name="description" ng-model="product.description"/>
<br>
<button ng-click="checkForm()">Check Form</button>
<br>
Form Pristine: {{output}}
<br><br>
I can see the description: {{descriptionTest}}
</form>
的問題是,我CTRL 2不能看到productForm。起初我以爲這曾與原型繼承做NG-包括做時,它能使孩子的範圍,所以我想在CTRL 2加入一個變量:
$scope.productForm = {};
這擺脫了錯誤的,但我的控制器仍然沒有正確地看到$ pristine或$ dirty。
我終於得到它的工作通過增加productForm高於$ scope.formHolder對象:
.controller('Ctrl2', function($scope) {
$scope.product = {description:'pump'};
$scope.output = 'unknown';
// uncomment to avoid undefined error, still can't see $pristine
$scope.formHolder = {};
$scope.checkForm = function() {
$scope.descriptionTest = $scope.product.description;
if ($scope.formHolder.productForm.$pristine) {
$scope.output = 'yes';
}
if ($scope.formHolder.productForm.$dirty) {
$scope.output = 'no'
}
}
});
HTML
<form name="formHolder.productForm" novalidate>
爲什麼這項工作?有沒有更好的方法來做到這一點?
我結束了這種方式,因爲我有一個工作表&控制器/模板,我想在其他地方重用。我應該做一個指令,但除了表單的$ pristine和$ dirty特徵之外,一切都正常工作 - 所有的ng-model vars都正確傳遞。
How can I set a form contained inside a ng-include to be prestine?有一個答案,「打破所有規則」,但似乎更復雜。
當我寫的時候,表單控制器添加$ pristine到範圍,以及什麼範圍?
編輯/答:
我原來的問題都可以歸結爲混淆形式指令如何寫入範圍。我的印象是,它將採取的東西
<form name="productForm">...
和屬性添加到它,就像
$scope.productForm.$pristine = function() {...}
但是
,它直接寫在productForm的頂部:
$scope.productForm = formObject;
所以,表單對象存儲在Child中,而不是按照所選答案中的說明存儲在父項中。
幫助我的子範圍繼承關鍵塊是鏈閱讀而不是書寫。所以如果你設置了類似childScope.myThing的東西。property ='123',雖然它看起來像寫,但它首先必須做一個閱讀,以找出myThing是什麼。而設置childScope.myThing ='567'是一個直接寫入,並且不涉及根本看父鏈。這一切更好地解釋在:What are the nuances of scope prototypal/prototypical inheritance in AngularJS?
在angularJS它是順路點符號。 – Walfrat