简体   繁体   English

AngularJS两个控制器…在页面加载时克服了$ scope。$ on

[英]AngularJS two controllers… overcoming $scope.$on when page loads

Still wrapping my head around AngularJS. 仍然把我的头围绕着AngularJS。 I have a pretty basic page which has two controllers. 我有一个漂亮的基本页面,其中包含两个控制器。 One has text input to take tags (for searching). 一个带有文本输入以获取标签(用于搜索)。 The other calls http.get(), using the tags to get the images... it does a bit of ordering and then they're displayed. 另一个调用http.get(),使用标签获取图像...它会进行一些排序,然后显示它们。 Following some info on the page below, I came up w/ something. 在下面页面上的一些信息之后,我想到了一些东西。 Can one controller call another? 一个控制器可以呼叫另一个控制器吗?

Caveat: It requires onClick() to execute. 注意:它需要onClick()才能执行。 Generally I want it to load up on page load with zero tags... and after a click with the tags. 通常,我希望它在页面加载时加载零标签...,然后单击标签。 I've seen a few suggestions in other threads here, but I'm not quite sure how to pull them off in this case. 我在这里的其他线程中看到了一些建议,但是我不太确定在这种情况下如何实现它们。 imagesController runs on load, but of course doesn't get past the 'handleBroadcast' bit. 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;
        });
    });
}

The HTML is quite trivial. HTML非常琐碎。 Slightly simplified, but it should suffice. 略有简化,但是就足够了。

<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>

Not sure I fully understood, but if you want to show it with no tags on load, simply emit the event when the controller loads: 不确定我是否完全理解,但是如果要在加载时不带标签显示它,只需在控制器加载时发出事件:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM