我有一個在我的DOM中多次執行的模板。AngularJS - 我的部分控制器
<div ng-controller="theController">
content does not matter
</div>
因此,控制器被隔離很多次。 這是一個問題,因爲如果我在控制器
theController = function($scope) {
$scope.$on('myVar', function() {
// run one time for each time the template is repeated
})
}
有關如何避免這種情況的任何想法把守望? 在此先感謝。
UPDATE
OK,我會盡量清晰。
也許我有一個表單,它是基於異步請求的響應動態構建的。
<form ng-controller="formController">
<div ng-repeat="f in fields">
<ng-inclide src="f.fields"></ng-include>
</div>
</form>
控制器是一樣的東西:
function formController($scope) {
$scope.fields = [{ template:'', ... }];
// data come from an ajax request...
// here are static for the sake of simplicity.
}
所以我不知道哪些字段的形式被追加。
表單字段結構存儲在HTML的諧音......是這樣的:
<div ng-controller="inputController">
<label> .... </label>
<input type="text" .... />
</div>
或
<div ng-controller="selectController">
<label> .... </label>
<select>
....
</select>
</div>
function selectController($scope){
$scope.$on("myCustomEvent", function(event) {
cionsole.info("Options were updated");
});
}
當表單具有比input type=text
或select
多,inputController
,或者selectController
被多次實例化。
爲什麼你不想每個實例都發生$ watch?
我想在發生特定事件時更新頁面中某個選項的選項。
我得到的是,而不是我更新頁面中的所有選擇。
從評論,我明白這是錯誤的,有更多元素與同一控制器在同一頁面。 因此,目前唯一可用的解決方案似乎是避免爲表單的每個元素定義控制器,對嗎?
UPDATE 2
$emit
在inputController使用:
function inputController() {
$scope.fireclick = function(p) {
if (p == 'specificInput') {
/* this is a temporary work around
I used to bind the event only with a specific field */
$scope.$emit("myCustomEvent");
}
}
}
這是輸入場的的HTML所使用的部分的完整代碼:
<input type="text" ng-click="fireclick(f.name);" name="{{f.name}}" />
@任何人:
至少可以確認,(最終說爲什麼),有相同的頁面上使用相同的控制器更多的元素是錯誤
控制器實例不能(也不應該)跨多個元素共享。你想要做什麼,爲什麼你不希望每個實例都出現'$ watch'?控制器本身就是你在DOM中使用它們的地方 - 它們不是在整個應用程序範圍內的 - 因此,如果多次觸發'$ watch'是一個問題,那麼你可能做錯了什麼。 – 2013-04-09 00:14:50
是一個boradcast/emit的事件 – 2013-04-09 09:02:11
@ArunPJohny我使用了$ rootScope。$ emit('myCustomEvent') – Bruno 2013-04-09 09:08:00