13-$location以及$interpolate等服务

但是在angularjs应用的网页中,提供一个$anchorScroll  用来做锚点的功能。比较简单,直接看例子:

<!DOCTYPE HTML>
<html ng-app="myApp">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<title>$anchorScroll</title>
<style type="text/css">
    #parent div{300px;height:500px;border:1px solid #000;border-radius:2px;margin:20px;}
    #parent ul{200px;position:fixed;top:0;right:0;}
    #parent ul li{margin:5px 0 ;}
</style>
<script type="text/javascript" src="js/angular.min.js"></script>
</head>
<body>

<div id="parent" ng-controller="Aaa">
    <ul>
        <li ng-repeat="id in [1,2,3,4,5,6]" ng-click="change('div'+id)">{{id}}</li>
    </ul>
    <div ng-repeat="id in [1,2,3,4,5,6]" ng-attr-id="div{{id}}">{{id}}</div>
</div>

<script type="text/javascript">

var m1 = angular.module('myApp',[]);
m1.config(['$anchorScrollProvider',function($anchorScrollProvider){
    $anchorScrollProvider.disableAutoScrolling();    //禁止跳转,控制区需要手动设置跳转$anchorScroll();
}]);
m1.controller('Aaa',['$scope','$location','$anchorScroll',function($scope,$location,$anchorScroll){
    $scope.change = function(id){
        console.log(id);
        $location.hash(id);
        $anchorScroll();
    };
}]);

</script>
</body>
</html>

点击右边的菜单,页面即定位到指定的DOM元素上。注意在m1的config上我们绑定了anchorScrollProvider,所以就不能更改地址栏触发描点定位了。需要的话就直接将$anchorScrollProvider.disableAutoScrolling();注释掉就好了。

 Angular的缓存服务,$cacheFactory:

<script type="text/javascript">
var m1 = angular.module('myApp',[]);
m1.controller('Aaa',['$scope','$cacheFactory',function($scope,$cacheFactory){
    
    var cache = $cacheFactory('myCache',{
        capacity : 2    //参数长度
    });
    cache.put('name','xiecg');    //设置
    cache.put('age',19);
    //cache.remove('name');        //删除
    console.log(cache.info());    //返回大小、id、一些缓存的参数
    //console.log(cache.get('name'));    //获取


}]);
</script>

这里唯一要注意的就是配置的capacity属性,假设参数的长度是1的话,数据也只能添加一条,再添加的不能获取。

日志服务:

<script type="text/javascript">

var m1 = angular.module('myApp',[]);
m1.controller('Aaa',['$scope','$log',function($scope,$log){

    $log.log(window);    //日志
    $log.info('info');    //提示
    $log.warn('warn');    //警告
    $log.error('error');//报错

}]);

</script>

插值服务:

<div ng-controller="Aaa">
    <input type="text" ng-model="name">
    <textarea ng-model="body"></textarea>
    <p>{{showText}}</p>
</div>
<script type="text/javascript">

var m1 = angular.module('myApp',[]);
m1.controller('Aaa',['$scope','$interpolate',function($scope,$interpolate){

    $scope.$watch('body',function(newBody){    //监听textarea输入的变化,返回newBody输入的内容
        if(newBody){
            var temp = $interpolate(newBody);
            //从输入框中拿到对应的值
            $scope.showText = temp({
                name : $scope.name
            });
        };
    });

}]);

</script>

我们在textarea中输入{{name}}会在下面的div中显示input输入框的内容。

学习笔记,如有不足,请指正!转载请保留原文链接,谢谢。

最後,微博求粉,谢谢。

原文地址:https://www.cnblogs.com/xiaoxie53/p/5076961.html