从指令的链接功能访问表单

时间:2014-11-27 19:08:19

标签: angularjs angularjs-directive

在我的自定义指令中,我声明了带有输入的新表单<div ng-form="inputForm"></div>。 如何在链接功能中访问此表单? scope.inputFormundefined:/

编辑:代码示例

&#13;
&#13;
.directive('ifInput', ['$system', function ($system) {
	return {
		restrict: "E",
		replace: true,
		scope: {},
		link: function (scope, element, attrs) {
			scope.temp = function () {
				console.log(scope.inputForm);
			}
		},
		templateUrl: "template/if-input-pola/index.html"
	};
}])
.run(["$templateCache", function ($templateCache) {
	$templateCache.put("template/if-input-pola/index.html",
		"<div ng-form=\"inputForm\" class=\"form-group ng-fadeInLeft\" ng-class=\"{'has-error': inputForm[kolumna.id].$invalid && inputForm.$dirty}\">" +
			"{{inputForm|json}}"+ //here is correct object (with $error and so on)
		"<a ng-click=\"temp()\">a</a>" + //here is undefined

		"</div>"
	);
}])
&#13;
&#13;
&#13;

编辑2: 问题是我要使用这样的对象ng-form="model.inputForm" - 现在一切正常

2 个答案:

答案 0 :(得分:0)

您可以定义ng-model,例如 <input ng-model="myInput">

link: function (scope, element) {
  console.log(scope.myInput);
}

答案 1 :(得分:0)

根据the documentation,使用ng-form="inputForm"应该将控制器发布在本地范围内。如果您看不到它,您要么在覆盖该属性的嵌套范围,要么在祖先范围内查看。请记住,某些指令(例如ng-repeatng-if)会创建本地范围,因此在以下代码中:

<div ng-controller="myController">
    <div ng-if="someCondition">
        <div ng-form="myInput">
            ...
        </div>
    </div>
</div>

myInput NOT 会在myController管理的范围内显示


link函数中访问scope属性时,它还取决于链接指令的位置,因为该属性可能尚未分配给范围。尝试$watch该属性,您可能会发现它稍后被分配。

相关问题