kiss-o-matic
kiss-o-matic

Reputation: 1181

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

Still wrapping my head around 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. Following some info on the page below, I came up w/ something. Can one controller call another?

Caveat: It requires onClick() to execute. 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.

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

Upvotes: 0

Views: 111

Answers (1)

Shomz
Shomz

Reputation: 37701

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("");
}

Upvotes: 1

Related Questions