angular js自定义service的简单示例

时间:2024-10-20 16:33:44
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script src="../materialDesignfile/angular.min.js"></script>
<script>
(function (angular) {
"use strict";
angular.module("myApp",[])
//自定义service层。
.service('myService',function () {
var name='ouyangfeng';
this.getName=function () {
return name;
}
this.add=function (x,y) {
return x+y;
}
})
//把service注入到controller层。
.controller("myCtrl",['$scope','myService',function ($scope,myService) {
$scope.sixi=function () {
alert(myService.getName());
}
$scope.village=function () {
alert(myService.add(3,5));
}
}])
})(window.angular);
</script>
<div ng-app="myApp" ng-controller="myCtrl" ng-cloak>
<button ng-click="sixi()">sixi</button>
<button ng-click="village()">village</button>
</div>
</body>
</html>