2016-09-20 7 views
0

考慮下面的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是intialized,compile應該呈現HTML和注入$scope

我有什麼問題嗎?

+1

父元素的控制器在子元素之前創建。一般來說,子元素應該與父元素「交談」,而不是相反。其他方式表明耦合。 –

回答

1

父元素的控制器將在子元素之前創建並鏈接。如果您希望父元素瞭解子窗體,你可能想要做這樣的事情:

<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。這種模式是共同的,所以常見的事實,角對組件綁定它(角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... 
} 

確定你想,雖然這樣做呢?如果您的父母元素與孩子這樣的元素對話,則可能表示高度耦合。你應該考慮讓溝通成爲另一種方式; 孩子組件告訴父母組件關於變化。

相關問題