Just do IT --- Angular(一)

Angular

<div ng-app="myApp" ng-controller="myCtrl">
    <input type="text" ng-model="firstName"><br>
</div>
<script>
var app = angular.module('myApp', []);//AngularJS 模块定义应用:
app.controller('myCtrl', function($scope) {//AngularJS 控制器控制应用:
    $scope.firstName= "John";
});
</script>

AngularJS控制器

1.function editController($scope, $http ,$routeParams) {php

}html

2.app.controller('editController', function($scope, $http ,$routeParams) {angularjs

});web

Angular模块加载

angular.module('myApp', [])
  .config(function($provide) { ...})
angular.module('myModule', []).
  value('a', 123).
  factory('a', function() { return 123; }).
  directive('directiveName', ...).
  filter('filterName', ...);

// Angular在编译时会执行这些函数,is same as

angular.module('myModule', []).
  config(function($provide, $compileProvider, $filterProvider) {
    $provide.value('a', 123);
    $provide.factory('a', function() { return 123; });
    $compileProvider.directive('directiveName', ...);
    $filterProvider.register('filterName', ...);
});
angular.module('myApp', [])
  .run(function($rootScope, AuthService) { 
     $rootScope.$on('$routeChangeStart', function(evt, next, current) {
        // If the user is NOT logged in
        if (!AuthService.userLoggedIn()) {
            if (next.templateUrl === "login.html") {
            // Already heading to the login route so no need to redirect
            } else { $location.path('/login');}
        }
      });
  });

AngularJS指令 ng-

ng-app指令定义了应用 模块(Module)
ng-controller 定义了控制器 控制器(Controller)
ng-model 指令用于绑定应用程序数据到 HTML 控制器(input, select, textarea)的值。
ng-bind 指令把应用程序数据绑定到 HTML 视图。
ng-init 指令初始化 AngularJS 应用程序变量。
ng-repeat 指令会重复一个 HTML 元素:
ng-disabled 指令直接绑定应用程序数据到 HTML 的 disabled 属性。api

建立自定义的指令
E 做为元素名使用
A 做为属性使用 数组


C 做为类名使用

M 做为注释使用

<runoob-directive></runoob-directive>

app.directive("runoobDirective", function() {
    return {
        restrict : "A",
        template : "<h1>自定义指令!</h1>"
    };
});
angular.module('myApp',[]).directive('zl1',[ function(){
  return {
    restrict:'AE',
    template:'thirective',
    link:function($scope,elm,attr,controller){
      console.log("这是link");
    },
    controller:function($scope,$element,$attrs){
      console.log("这是con");
    }
  };
}]).controller('Con1',['$scope',function($scope){
  $scope.name="aliceqqq";
}]);

AngularJS做用域 $scope

AngularJS 应用组成以下:
View(视图), 即 HTML。
Model(模型), 当前视图中可用的数据。
Controller(控制器), 即 JavaScript 函数,能够添加或修改属性。
$scope(做用域) 是应用在 HTML (视图) 和 JavaScript (控制器)之间的纽带。
$rootScope (根做用域) 可做用于整个应用中。是各个 controller 中 scope 的桥梁。用 rootscope 定义的值,能够在各个 controller 中使用。服务器

AngularJS控制器

AngularJS过滤器

currency 格式化数字为货币格式。
filter 从数组项中选择一个子集。
lowercase 格式化字符串为小写。
orderBy 根据某个表达式排列数组。
uppercase 格式化字符串为大写。app

<p><input type="text" ng-model="test"></p>
<ul>
  <li ng-repeat="x in names | filter:test | orderBy:'country'">
    {{ (x.name | uppercase) + ', ' + x.country }}
  </li>
</ul>

AngularJS服务(Service)

$location 返回当前页面的 URL 地址
$scope.myUrl = $location.absUrl();框架

$http 向服务器发送请求,应用响应服务器传送过来的数据。ide

$http.get('/someUrl', config).then(successCallback, errorCallback);
$http.post('/someUrl', data, config).then(successCallback, errorCallback);

app.controller('siteCtrl', function($scope, $http) {
    $http({
        method: 'GET',
        url: 'https://www.runoob.com/try/angularjs/data/sites.php'
    }).then(function successCallback(response) {
            $scope.names = response.data.sites;
        }, function errorCallback(response) {
            // 请求失败执行代码
    });
  
});


app.controller('myCtrl', function($scope, $http) {
    $http.get('/api/todos')
        .success(function(data) {
            $scope.todo = data[index];  
        })
        .error(function(data) {
            console.log('Error: ' + data);
        });
});

$timeout 服务对应了 JS window.setTimeout 函数。

app.controller('myCtrl', function($scope, $timeout) {
    $scope.myHeader = "Hello World!";
    $timeout(function () {
        $scope.myHeader = "How are you today?";
    }, 2000);
});

$interval 服务对应了 JS window.setInterval 函数
app.controller('myCtrl', function($scope, $interval) {
  $scope.theTime = new Date().toLocaleTimeString();
  $interval(function () {
      $scope.theTime = new Date().toLocaleTimeString();
  }, 1000);
});

.service建立自定义服务

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

过滤器中,使用自定义服务

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="https://cdn.static.runoob.com/libs/angular.js/1.4.6/angular.min.js"></script>
</head>
<body>

<div ng-app="myApp">
在过滤器中使用服务:

<h1>{{255 | myFormat}}</h1>

</div>

<script>
var app = angular.module('myApp', []);
app.service('hexafy', function() {
    this.myFunc = function (x) {
        return x.toString(16);
    }
});
app.filter('myFormat',['hexafy', function(hexafy) {
    return function(x) {
        return hexafy.myFunc(x);
    };
}]);

</script>

</body>
</html>

$watch:持续监听数据上的变化,更新界面

<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>

事件

ng-click : ng-click="toggle()"
ng-hide
ng-show

包含

AngularJS 路由

AngularJS 路由容许咱们经过不一样的 URL 访问不一样的内容。
经过 AngularJS 能够实现多视图的单页Web应用(single page web application,SPA)。
一般咱们的URL形式为 http://runoob.com/first/page,但在单页Web应用中 AngularJS 经过 # + 标记 实现,例如:
http://runoob.com/#/first
1.须要 js 文件:angular-route.js
二、包含了 ngRoute 模块做为主应用模块的依赖模块。
angular.module('routingDemoApp',['ngRoute'])

三、使用 ngView 指令。

四、配置 $routeProvider,AngularJS $routeProvider 用来定义路由规则。
module.config(['$routeProvider', function($routeProvider){
$routeProvider
.when('/',{template:'这是首页页面'})
.when('/computers',{template:'这是电脑分类页面'})
.when('/printers',{template:'这是打印机页面'})
.otherwise({redirectTo:'/'});
}]);

angular 应用经常使用哪些路由库,各自的区别是什么?

Angular1.x 中经常使用 ngRoute 和 ui.router,还有一种为 Angular2 设计的 new router (面向组件)。后面那个没在实际项目中用过,就不讲了。
不管是 ngRoute 仍是 ui.router,做为框架额外的附加功能,都必须以 模块依赖 的形式被引入。
区别
ngRoute 模块是 Angular 自带的路由模块,而 ui.router 模块是基于 ngRoute模块开发的第三方模块。
ui.router 是基于 state (状态)的, ngRoute 是基于 url 的,ui.router模块具备更强大的功能,主要体如今视图的嵌套方面。
使用 ui.router 可以定义有明确父子关系的路由,并经过 ui-view 指令将子路由模版插入到父路由模板的

中去,从而实现视图嵌套。而在 ngRoute 中不能这样定义,若是同时在父子视图中 使用了
会陷入死循环。

ngRoute

var app = angular.module('ngRouteApp', ['ngRoute']);
app.config(function($routeProvider){
    $routeProvider
        .when('/main', {
            templateUrl: "main.html",
            controller: 'MainCtrl'
        })
        .otherwise({ redirectTo: '/tabs' });
ui.router

var app = angular.module("uiRouteApp", ["ui.router"]);
app.config(function($urlRouterProvider, $stateProvider){
    $urlRouterProvider.otherwise("/index");
    $stateProvider
        .state("Main", {
            url: "/main",
            templateUrl: "main.html",
            controller: 'MainCtrl'
        })
相关文章
相关标签/搜索