angularJs service

有关angular service初步学习笔记:首先,要把service对象作为参数传给controller

var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $location) {
    $scope.myUrl = $location.absUrl();
});

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
    $http.get("welcome.htm").then(function (response) {
        $scope.myWelcome = response.data;
    });
});

 

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
    $http.get("welcome.htm").then(function (response) {
        $scope.myWelcome = response.data;
    });
});

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
    $http.get("welcome.htm").then(function (response) {
        $scope.myWelcome = response.data;
    });
});

 

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="http://cdn.static.runoob.com/libs/angular.js/1.4.6/angular.min.js"></script>
</head>
<body>
<div ng-app="myApp" ng-controller="myCtrl">

<p>255 的16进制是:</p>

<h1>{{hex}}</h1>

</div>

<p>自定义服务,用于转换16进制数:</p>

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

app.service('hexafy', function() {
this.myFunc = function (x) {
return x.toString(16);
}
});
app.controller('myCtrl', function($scope, hexafy) {
$scope.hex = hexafy.myFunc(255);
});
</script>

</body>
</html>

 

当你创建了自定义服务,并连接到你的应用上后,你可以在控制器,指令,过滤器或其他服务中使用它。

在过滤器 myFormat 中使用服务 hexafy:

app.filter('myFormat',['hexafy'function(hexafy) {
    return function(x) {
        return hexafy.myFunc(x);
    };
}]);
 

<body>

<div ng-app="myApp" ng-controller="myCtrl">

<p>现在时间是:</p>

<h1>{{theTime}}</h1>

</div>

<p>上述代码是不使用 $interval 服务的情况下,运用 $apply,实现每一秒显示信息的功能。</p>

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.theTime = new Date().toLocaleTimeString();
$scope.setTime = function() {
// $apply 方法可以修改数据
$scope.$apply(function() {
$scope.theTime = new Date().toLocaleTimeString();
});
};
setInterval($scope.setTime, 1000);
});
</script>

<head>
<meta charset="utf-8">
<script src="http://cdn.static.runoob.com/libs/angular.js/1.4.6/angular.min.js"></script>
</head>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<b>请输入姓名:</b><br>
<b>姓:</b><input type="text" ng-model="lastName"><br>
<b>名:</b><input type="text" ng-model="firstName"><br>
<h1>{{ lastName + " " + firstName }}</h1>
<h2>{{ fullName }}</h2>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.lastName = "";
$scope.firstName = "";

//监听lastName的变化,更新fullName
$scope.$watch('lastName', function() {
$scope.fullName = $scope.lastName + " " + $scope.firstName;
});

//监听firstName的变化,更新fullName
$scope.$watch('firstName', function() {
$scope.fullName = $scope.lastName + " " + $scope.firstName;
});
});
</script>
</body>

 

 

posted @ 2017-07-07 08:50  猪阿南  阅读(75)  评论(0编辑  收藏  举报