![](/img/trans.png)
[英]$scope.$apply not working when injecting html with scope variables - AngularJs
[英]AngularJS two controllers… overcoming $scope.$on when page loads
仍然把我的頭圍繞着AngularJS。 我有一個漂亮的基本頁面,其中包含兩個控制器。 一個帶有文本輸入以獲取標簽(用於搜索)。 另一個調用http.get(),使用標簽獲取圖像...它會進行一些排序,然后顯示它們。 在下面頁面上的一些信息之后,我想到了一些東西。 一個控制器可以呼叫另一個控制器嗎?
注意:它需要onClick()才能執行。 通常,我希望它在頁面加載時加載零標簽...,然后單擊標簽。 我在這里的其他線程中看到了一些建議,但是我不太確定在這種情況下如何實現它們。 imagesController在負載下運行,但是當然不會超過'handleBroadcast'位。
var myModule = angular.module('myModule', []);
myModule.run(function($rootScope) {
$rootScope.$on('handleEmit', function(event, args) {
$rootScope.$broadcast('handleBroadcast', args);
});
});
function tagsController($scope) {
$scope.handleClick = function(msg) {
$scope.tags = msg;
$scope.$emit( 'handleEmit', { tags: msg });
};
}
function imagesController($scope,$http) {
$scope.$on('handleBroadcast', function(event, args) {
$scope.tags = args.tags;
var site = "http://www.example.com";
var page = "/images.php";
if ( args.tags ) {
page += "?tags=" + $scope.tags;
}
$http.get(site+page).success( function(response) {
// SNIP
$scope.data = response;
});
});
}
HTML非常瑣碎。 略有簡化,但是就足夠了。
<form name="myForm" ng-controller="tagsController">
<div class="left_column">
<input class="textbox_styled" name="input" data-ng-model="tags"><br>
<button ng-click="handleClick(tags);">Search</button><br>
</div>
</form>
<div class="centered" data-ng-controller="imagesController">
<span class="" data-ng-repeat="x in data">
{{x}}
</span>
</div>
不確定我是否完全理解,但是如果要在加載時不帶標簽顯示它,只需在控制器加載時發出事件:
function tagsController($scope) {
$scope.handleClick = function(msg) {
$scope.tags = msg;
$scope.$emit( 'handleEmit', { tags: msg });
};
$scope.$emit( 'handleEmit', { tags: "" }); // or $scope.handleClick("");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.