AngularJS中的服务无效

时间:2016-01-07 16:17:28

标签: javascript angularjs angularjs-service

我致力于最简单的基于AngularJS app的方法来理解它的流程。我试图将简单的字符串从服务传递到控制器,并从那里我想在index.html中打印此字符串。似乎我的其余代码正在工作,但没有服务,也不确定我在这里缺少什么...

的index.html

<!DOCTYPE html>
<html ng-app="angularFormsApp">
 <head>
 <title>Angular Form</title>
 <meta charset="utf-8" />
  <link href="Content/bootstrap.min.css" rel="stylesheet" />
  <script src="Scripts/angular.min.js"></script>
  <script src="App/AngularFormsApp.js"></script>
  <script src="App/EmployeeForm/efService.js"></script>
  <script src="App/EmployeeForm/efController.js"></script>

<!--<script src="App/EmployeeForm/efDirective.js"></script>
-->
</head>
  <body>
     <h1>Test AngularJS App Approach</h1>

   <div ng-controller="efController">
       {{employee}}
   </div>

</body >
</html>

AngularFormsApp.JS(模块)

var angularFormsModule = angular.module('angularFormsApp', []);

efController.js(Controller)

angularFormsModule.controller('efController',
  function efController($scope, efService) {

    $scope.employee = efService.employee;
});

efService.js(服务)

angularFormsModule.factory('efService',
 function () {
    var employee = "Employee Detail Available";

    return employee;
});

3 个答案:

答案 0 :(得分:5)

您可能希望返回一个对象而不是字符串。

angularFormsModule.factory('efService',
function efService() {
    var service = {
        employee: "Employee Detail Available"
    }
    return service;
});

答案 1 :(得分:1)

当您致电$to = array($_POST['email'],'foo@bar.com'); 时,您需要返回一个对象,该对象包含要使用此工厂实例从外部访问的factoryproperties

methods

答案 2 :(得分:1)

您实际上是在控制器中调用了服务未公开的本地服务变量:

 $scope.employee = efService.employee;

您要在工厂返回一个功能,因此您应该在控制器中使用它:

 $scope.employee = efService();