search

Home  >  Q&A  >  body text

angular.js - How to call service externally in Angularjs

I wrote a piece of angularjs code to inject service into the controller, roughly like this:

window.app = angular.module('myApp', []);
app.controller('Ctrl',function($scope, Service){
    $scope.test = Service.test();
});
app.factory('Service',function(){
    var test= 1;
    var service={};
    service.testing= function(){
        return test;
    }
});

This code is placed under a <script></script> tag in the body of an html, and the test can be implemented. But if I put

app.factory('Service',function(){
    var test= 1;
    var service={};
    service.testing= function(){
        return test;
    }
});

Put it forward, there is no way to implement it by putting it in an a.js file alone. I tried putting <script language=javascript src=“/js/a.js”></script> in the header; it didn’t work if I put it in the body above or below the script tag with the controller. Do I need to reference this file into the script tag? How to write it?

PHPzPHPz2840 days ago534

reply all(1)I'll reply

  • 黄舟

    黄舟2017-05-15 17:08:28

    Write this in a separate js file: angular.module('myApp').factory('Service', function() {//...})

    reply
    0
  • Cancelreply