AngularJs $anchorScroll、$controller、$document

简介: $anchorScroll 根据HTML5的规则,当调用这个函数时,它检查当前的url的hash值并且滚动到相应的元素。 监听$location.hash()并且滚动到url指定的锚点的地方。可以通过$anchorScrollProvider.disableAutoScrolling()禁用。

$anchorScroll

根据HTML5的规则,当调用这个函数时,它检查当前的url的hash值并且滚动到相应的元素。

监听$location.hash()并且滚动到url指定的锚点的地方。可以通过$anchorScrollProvider.disableAutoScrolling()禁用。

依赖:$window   $location   $rootScope

使用:$anchorScroll();

使用代码:

  #id {height:500px;}
  #bottom {margin-top:1500px;}
  <div ng-app="Demo" ng-controller="testCtrl as ctrl">
      <div id="top" ng-click="ctrl.gotoBottom()">跳到底部</div>
      <div id="bottom" ng-click="ctrl.gotoTop()">跳到顶部</div>
  </div>
  (function () {
    angular.module("Demo", [])
    .controller("testCtrl",["$location", "$anchorScroll",testCtrl]);
    function testCtrl($location,$anchorScroll){
      this.gotoTop = function () {
        $location.hash("top");
        $anchorScroll();
      };
      this.gotoBottom = function () {
        $location.hash("bottom");
        $anchorScroll();
      };
    };
  }());

$controller

$controller负责实例化控制器。

这只是个简单的$injector调用,但为了以前版本的这个服务能被覆盖而被提取进一个服务。

依赖:$injector

使用:$controller(constructor,locals);

constructor:如果调用了一个函数,那么这个函数被认为是控制器构造函数。否则,它被认为是一个使用以下步骤检索控制器的构造函数的字符串:

1.检查控制器是否在$controllerProvider注册并命名。

2. 检查当前作用域上的字符串是否返回一个构造函数

3.在全局window对象上检查构造器。

locals:Object,将需要调用的控制器注册到当前控制器。

使用代码:

  (function () {
    angular.module("Demo", [])
    .controller("demoCtrl",["$scope",demoCtrl])
    .controller("testCtrl",["$controller","$scope",testCtrl]);
    function demoCtrl($scope){
        $scope.print = function () {
            console.log("print");
        };
        this.prt = function () {
            $scope.print();
        };
    };
    function testCtrl($controller,$scope){
        var ctrl = $controller("demoCtrl",{$scope:$scope});
        ctrl.prt(); // print
    };
  }());

$document

一个jQuery或jqlite包装了的浏览器window.document对象。

依赖:$window

使用代码:

<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <script src='angular.js'></script>
    <title>title-$document</title>
</head>
<body>
  <div ng-app="Demo" ng-controller="testCtrl as ctrl"></div>
  <script>
  (function () {
    angular.module("Demo", [])
    .controller("testCtrl",["$document",testCtrl]);
    function testCtrl($document){
        var $title = $document[0].title;//title-$document
        var title = angular.element(window.document)[0].title;//title-$document
        var v = $document[0] === window.document;//true
    };
  }());
  </script>
</body>
</html>

这两天被$animate和$interpolate还有$http给折腾的心累啊,有一小部分代码还没测出来,所以先把这三个内容少点的整合到一篇文章先总结了先。明天看看花点时间把那三个给写完整吧,估计需要分三篇文章来记录$animate、$interpolate和$http呢。

相关文章
|
5月前
|
JavaScript
AngularJS ng-if使用
AngularJS ng-if使用
|
JavaScript
AngularJs错误http://errors.angularjs.org/1.2.9/$injector/unpr?p0=...
AngularJs错误http://errors.angularjs.org/1.2.9/$injector/unpr?p0=...
62 0
|
JavaScript 容器 前端开发
|
Web App开发 JavaScript 前端开发
|
JavaScript 前端开发 移动开发
|
JSON 前端开发 API