为什么在angular的控制器初始化期间form object不可用?
Why is form object not available during controller initialization in angular?
考虑以下html
<div ng-app="myApp" ng-controller="myController">
<form name="myForm"></form>
</div>
和控制器文件
(function () {
'use strict';
angular
.module('myApp')
.controller('myController', myController);
myController.$inject = ['$scope', '$interval'];
function myController($scope, $interval) {
var myFormDetector = $interval(function() {
if ($scope.myForm) {
console.log('form exist');
$interval.cancel(myFormDetector);
} else {
console.log('form not exist');
}
}, 200)
}
})();
我观察到form not exist
至少打印一次?
这很奇怪,因为我认为渲染的顺序是
compile
controller
link
所以当controller
初始化时,compile
应该渲染html并注入$scope
?
我写错什么了吗?
父元素的控制器将在子元素之前创建并链接。如果您希望父元素知道子表单的信息,您可能需要这样做:
<div ng-app='myApp' ng-controller='myController'>
<form name='myForm' ng-init='myController.onInit()'>
</form>
</div>
function MyController($scope) {
this.$scope = $scope
}
MyController.prototype.onInit = function onInit() {
this.$scope.myForm....
}
这不是很可持续,但它被认为是坏的做法使用ngController
这样。这种模式很常见,以至于Angular已经为它的组件绑定了(Angular 1.5+)
<div ng-app='myApp'>
<x-parent-component>
<form name='ngForm'>
</form>
</x-parent-component>
</div>
angular.module('myApp', [])
.component('xParentComponent', {
controller: XParentComponentCtrl,
transclude: true,
template: '<div ng-transclude></ng-transclude>'
})
function XParentComponentCtrl($scope) {
this.$scope = $scope
}
XParentComponentCtrl.prototype.$postLink = function $postLink() {
this.$scope.myForm...
}
你确定你想这么做吗?如果您的父元素像这样与子元素对话,这可能表示高耦合。你可能应该考虑用另一种方式进行交流;子组件告诉父组件变化。
相关文章:
- 函数未在Object.keys或Object.getOwnPropertyNames下列出,但可以调用
- Dojo:访问dijit.form.Select中单击的项目
- delete在Object上效率低下,但在DOM Element's的数据属性,与null out相比
- Javascript form innerHTML
- 有没有一种方法可以列出Ember.Object的所有绑定
- 如何取消object.prototypes javascript的一个函数
- 无法在有条件呈现的富:面板上提交h:form
- 为什么是文档.旧版应用程序中的DOM-object.properties为null
- 将*.js文件的内容放入Object中
- Object.prototype using 'this'
- Javascript form.submit()方法是如何工作的
- 使用Object.create()的角度服务继承
- 如何使用object.assign()从其他对象引用基本对象属性
- 循环的数组推入在Object容器中具有不同的值
- reducers在redux中得到Function not Object,what'it’他错了
- 通过jQueryAjax一起发布Array和Form数据时出现问题
- JSON.stringify和Object.keys在同一个对象上产生不同的结果
- This.Form.Submit() on CakePHP
- 为什么在angular的控制器初始化期间form object不可用?
- Google Closure - Form data to json object