AngularJs简单的自定义服务不起作用

时间:2016-03-14 22:01:39

标签: javascript angularjs angular-services

我是角色新手并尝试创建新的自定义服务并在视图上提取数据。这可能是什么问题?

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta charset="utf-8" />
    <script src="Scripts/angular.min.js"></script>
</head>
<body ng-app="myApp" ng-controller="myCtrl">
    service data is {{serviceData}}
</body>
</html>


<script>
    var app = angular.module('myApp', []);

    app.controller('myCtrl', function ($scope, myService) {       
        $scope.serviceData = myService.getDetails;
    });

    app.factory('myService', function () {
        return
        {
            getDetails: "I am testing service....";
        };
    });

</script>

1 个答案:

答案 0 :(得分:4)

请从getDetails属性声明

中删除分号

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

app.controller('myCtrl', function($scope, myService) {
  $scope.serviceData = myService.getDetails;
});

app.factory('myService', function() {
  return {
    getDetails: "I am testing service...."
  };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="myApp" ng-controller="myCtrl">
  service data is {{serviceData}}
</div>