我有一個Angular指令,其中包含一個帶有驗證的表單。我想在我的視圖中有一個按鈕,當這個指令的形式爲$pristine
時,它會被禁用,但是按鈕存在於控制器級別的視圖中,所以我無法訪問指令中的子窗體。如何從控制器訪問指令中的表單?
如何從父控制器訪問指令中的表單而不做一些奇怪的破解?
我有一個Angular指令,其中包含一個帶有驗證的表單。我想在我的視圖中有一個按鈕,當這個指令的形式爲$pristine
時,它會被禁用,但是按鈕存在於控制器級別的視圖中,所以我無法訪問指令中的子窗體。如何從控制器訪問指令中的表單?
如何從父控制器訪問指令中的表單而不做一些奇怪的破解?
這裏就是一個很好的辦法做到這一點。公開一個指令控制器,就像在當前作用域上公開FormController
對象一樣。由於您的指令創建隔離範圍,代碼看起來像:
controller:function($scope, $element, $attrs) {
$scope.$parent[$attrs.myDirectiveName]=this; // Exposes the directive controller on the parent scope with name myDirectiveName
// Now you can define a function that tells state of the form. Or expose the form on the controller
this.isPristine=function() {
return $scope.formName.$pristine;
}
}
一旦指令控制器是存在的,你附加指令到html元素和控制器可在當前範圍。
<div my-directive='mydir'></div> // create a property $scope.mydir on current scope.
現在你可以使用$scope.mydir.isPristine()
爲什麼不直接添加到按鈕NG-禁用
小提琴:http://jsfiddle.net/4vhsmdcn/
<div ng-controller="MyCtrl">
<form name="bob">
<input name="some" type="text" ng-model="pie"/>
<button ng-disabled="bob.$pristine">Submit</button>
</form>
</div>
檢查就像我說的國家,形式內部存在一個指令,這意味着它的FormController的範圍僅因爲它使用一個孤立的範圍是指令中存在 – 2014-12-03 02:04:25
這會起作用,但它是否違背角度想要被使用? – 2014-12-03 17:46:41
不知道你是什麼意思。通過這種方法,您可以通過控制器暴露指令API,並將其添加到範圍中。它與Angular'form'指令是如何相似的。 – Chandermani 2014-12-04 01:42:10