1

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?

3
  • No unfortunately you have to inject them in every controller that requires those dependencies. That's just how angular works. As for your second question, that would be an angular module. Commented Jul 22, 2016 at 2:54
  • @hsiung, i see, can you tell me if there is a way I can make my own expression and use it in different controllers? Without having to initialize it in each controller Commented Jul 22, 2016 at 2:56
  • You can inherit controllers Most suggest using services and emitting events on the scope to communicate between controllers Commented Jul 22, 2016 at 3:23

3 Answers 3

1

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="[email protected]" 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="[email protected]" 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>

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, this is what I wanted. I really appreciate you pasting all the codes, it helped me understand better!
0

In AngularJS you have to inject your dependencies into each controller. In that way, each controller only has exactly the dependencies that it needs instead of any extraneous ones.

The line

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

is just how you tell AngularJS that you want to make a new module. Then to add things to the module you just make calls like

app.controller('controllerName', function() {/* your stuff here */});
app.filter('filterName', function() {/* your stuff here */});

2 Comments

Thank you for your answer. I have another question then, is there a way I can make my own expression and use it in different controllers? Without having to initialize it in each controller
Yeah, take a look at the new answer I just posted.
0

To make your own expression and use it in other parts of your code try something like this:

var myApp=angular.module('myApp', []);
myApp.value('clientId', 'a12345654321x'); // this sets a value

Then if you include clientId as a dependency anywhere it would be equal to a12345654321x wherever it was injected.

To use your value in other places just include it as a dependency

myApp.controller('mycontroller', ['clientId', function(clientId) {
    console.log(clientId);
}]);

For more complex behaviors you can get into other types of AngularJS providers like factories. Here's the docs for reference: https://docs.angularjs.org/guide/providers

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.