Angularjs injecting Services into controllers detailed _angularjs

Source: Internet
Author: User


The method of loading the service into the controller as a dependent resource is very similar to the method that is loaded into other services.



Because JavaScript is a dynamic language, Di cannot figure out which service should be injected through the static types (like in static typed languages). Therefore, we need to specify the service name through the $inject property, which is an array of strings containing the service names that need to be injected. Importance of Service ID order: The order of the parameters in the factory method, consistent with the order of the service in the array. The parameter names of the factory methods are not important, but they match the service ID one by one as usual, and the benefits of doing so are discussed below.



1. Explicit-Dependency Injection


function Mycontroller ($scope, $loc, $log) {
$scope. FirstMethod = function () {
  ///Use $location service
   $loc. s  Ethash ();
  };
$scope. Secondmethod = function () {
    ///Use $log service
    $log. info (' ... ')
};
}
Mycontroller $inject = [' $location ', ' $log '];  


Example:


<! DOCTYPE HTML>
<html lang = "zh-cn" ng-app = "MainApp">
<head>
  <meta charset = "UTF-8">
  <title> explicit-inject-service </ title>
</ head>
<body>
<div ng-controller = "MyController">
  <input type = "text" ng-model = "msg" />
  <button ng-click = "saveMsg ()"> save msg </ button>
  <ul>
    <li ng-repeat = "msg in msgs"> {{msg}} </ li>
  </ ul>
</ div>
<script src = "../ angular-1.0.1.js" type = "text / javascript"> </ script>
<script type = "text / javascript">
  var app = angular.module ("MainApp", [], function ($ provide) {
    $ provide.factory ("notify", ["$ window", "$ timeout", function (win, timeout) {
      // This is a service dependent service. In this explicit way, parameter names can be filled in randomly, but the order must correspond
      var msgs = [];
      return function (msg) {
        msgs.push (msg);
        if (msgs.length == 3) {
          timeout (function () {
            win.alert (msgs.join ("\ n"));
            msgs = [];
          }, 10);
        }
      }
    }]);
  });

  function MyController ($ s, $ noti) {
    // Here is the controller dependent service. In this explicit way, the parameter names can be filled in randomly, but the order must correspond
    $ s.msgs = [];
    $ s.saveMsg = function () {
      this.msgs.push (this.msg);
      $ noti (this.msg);
      this.msg = "";
    };
  }
  // Specify the injected stuff
  // You can also refer to the example in http://www.cnblogs.com/lcllao/archive/2012/10/16/2725317.html
  MyController. $ Inject = ['$ scope', 'notify'];

</ script>
</ body>
</ html>


2. Implicit-Dependency Injection



A new feature of angular di that allows dependencies to be determined by parameter names. Let's rewrite the example above to show how to implicitly inject $window, $scope and notify service.



Example:


<! DOCTYPE HTML>
<html lang = "zh-cn" ng-app = "MainApp">
<head>
  <meta charset = "UTF-8">
  <title> implicit-inject-service </ title>
</ head>
<body>
<div ng-controller = "MyController">
  <input type = "text" ng-model = "msg" />
  <button ng-click = "saveMsg ()"> save msg </ button>
  <ul>
    <li ng-repeat = "msg in msgs"> {{msg}} </ li>
  </ ul>
</ div>
<script src = "../ angular-1.0.1.js" type = "text / javascript"> </ script>
<script type = "text / javascript">
  var app = angular.module ("MainApp", [], function ($ provide) {
    $ provide.factory ("notify", function ($ window, $ timeout) {
      // The service depends on the service, implicitly dependent, the name can be the same
      var msgs = [];
      return function (msg) {
        msgs.push (msg);
        if (msgs.length == 3) {
          $ timeout (function () {
            $ window.alert (msgs.join ("\ n"));
            msgs = [];
          }, 10);
        }
      }
    });
  });

  function MyController ($ scope, notify) {
    // The service depends on the service, implicitly dependent, the name can be the same
    $ scope.msgs = [];
    $ scope.saveMsg = function () {
      this.msgs.push (this.msg);
      notify (this.msg);
      this.msg = "";
    };
  }
</ script>
</ body>
</ html> 


While this is convenient, if we need to compress and confuse our code, which may cause the parameter names to be changed, we still need to use explicit declaration dependencies when we encounter this situation.



The above is about ANGULARJS injecting Services into controllers data collation, follow-up continue to supplement the relevant information, thank you for your support of this site!


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.