AngularJS两个控制器..克服$scope$页面加载时打开

AngularJS two controllers... overcoming $scope.$on when page loads

本文关键字:scope 加载 克服 控制器 两个 AngularJS      更新时间:2023-09-26

我的头还在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("");
}