noor noor - 4 months ago 26
AngularJS Question

AngularJS passing objects from main controllers to other controllers

I am new to Angularjs and Ionic. I am currently building my first app and I want to know, is there any way I can inject expressions in the main controller and use them in all the other controllers.

So instead of typing $scope, $http, $Ionicpopup in every controller. I want to put that in my main controller and use them in all other controllers.


var app=angular.module('app.controllers', []);


Can you tell me what this is called?

Win Win
Answer

We normally use service to communicate between controllers.

In the following sample example, we create animalService, and inject it to both controllers. We then use $watch to monitor the changes.

http://plnkr.co/edit/hfKuxJO2XZdB6MsK7Ief

(function () {

    angular.module("root", [])
      .controller("leftAnimal", ["$scope", "animalService",
        function ($scope, animalService) {

            $scope.findNewAnimal = function () {
                var randNum = Math.floor(Math.random() * animalPool.length);
                $scope.animal = animalPool[randNum];
                console.log("Left Click Index: " + randNum);
                animalService.setAnimal(randNum);
            };

            $scope.$watch(function () {
                return animalService.getAnimal();
            }, function (value) {
                $scope.animal = animalPool[value];
            });
        }
      ])
      .controller("rightAnimal", ["$scope", "animalService",
        function ($scope, animalService) {

            $scope.findNewAnimal = function () {
                var randNum = Math.floor(Math.random() * animalPool.length);
                $scope.animal = animalPool[randNum];
                console.log("Right Click Index: " + randNum);
                animalService.setAnimal(randNum);
            };

            $scope.$watch(function () {
                return animalService.getAnimal();
            }, function (value) {
                $scope.animal = animalPool[value];
            });
        }
      ])
      .factory("animalService", [function () {
          var index = 0;
          function getAnimal() {
              return index;
          }
          function setAnimal(newIndex) {
              index = newIndex;
          }
          return {
              getAnimal: getAnimal,
              setAnimal: setAnimal,
          }
      }]);

    var animalPool = [{
        name: "Baby Quetzal",
        img: "http://i.imgur.com/CtnEDpM.jpg",
        baby: true
    }, {
        name: "Baby Otter",
        img: "http://i.imgur.com/1IShHRT.jpg",
        baby: true
    }, {
        name: "Baby Octopus",
        img: "http://i.imgur.com/kzarlKW.jpg",
        baby: true
    }];
})();
<!DOCTYPE html>
<html ng-app="root">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <link data-require="bootstrap-css@3.3.6" data-semver="3.3.6" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.css" />
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="angular.js@1.4.x" src="https://code.angularjs.org/1.4.9/angular.js" data-semver="1.4.9"></script>
    <script src="app.js"></script>
  </head>

  <body>
     <div class="row">
        <div class="text-center">
            <h2>Pick an Animal</h2>
        </div>
        <div ng-controller="leftAnimal" class="col-md-6">
            <div class="animalImage">
                <img class="img-center" ng-src="{{animal.img}}"/>
            </div>
            <div class="animalName">{{animal.name}}</div>
            <div class="animalDescription">{{animal.description}}</div>
            <button type="button" ng-click="findNewAnimal()"
                    class="btn btn-info img-center">
                Change
            </button>
        </div>
        <div ng-controller="rightAnimal" class="col-md-6">
            <div class="animalImage">
                <img class="img-center" ng-src="{{animal.img}}" />
            </div>
            <div class="animalName">{{animal.name}}</div>
            <div class="animalDescription">{{animal.description}}</div>
            <button type="button" ng-click="findNewAnimal()"
                    class="btn btn-info img-center">
                Change
            </button>
        </div>
    </div>
  </body>

</html>

Comments