Angular based learning

  1. ng-init:
    Math:

     <div ng-app="" ng-init="quantity=1;cost=5">
     	<p>总价: <span ng-bind="quantity * cost"></span></p>
     </div>
    

    String manipulation:

     <div ng-app="" ng-init="firstName='John';lastName='Doe'">
     	<p>姓名: {{ firstName + " " + lastName }}</p>
     </div>
    
  2. of Binding:

     ng-init="points=[1,15,19,2,40]"    // {{ points[2] }},<span ng-bind="points[2]"></span>
     ng-init="person={firstName:'John',lastName:'Doe'}"
     <div ng-app="" ng-init="firstName='John';lastName='Doe'">
     	<p>姓名: <span ng-bind="firstName + ' ' + lastName"></span></p>
     </div>
    
  3. ng-model: (Dynamic listens for incoming data)

     <div ng-app="" ng-init="firstName='John'">
      <p>在输入框中尝试输入:</p>
      <p>姓名:<input type="text" ng-model="firstName"></p>
      <p>你输入的为: {{ firstName }}</p>
     </div>
     
     验证:
     	<form ng-app="" name="myForm" ng-init="myText = '[email protected]'">
     		Email:
     		<input type="email" name="myAddress" ng-model="myText" required></p>
     		<h1>状态</h1>
     		{{myForm.myAddress.$valid}}
     		{{myForm.myAddress.$dirty}}
     		{{myForm.myAddress.$touched}}
     	</form>
     css:
     	<style>
     		input.ng-invalid {
     			background-color: lightblue;
     		}
     	</style>
     	<body>
    
     	<form ng-app="" name="myForm">
     		输入你的名字:
     		<input name="myAddress" ng-model="text" required>
     	</form>
    
  4. a repeat

    <div ng-app="" ng-init="names=[
    {name:'Jani',country:'Norway'},
    {name:'Hege',country:'Sweden'},
    {name:'Kai',country:'Denmark'}]">
     
    <p>循环对象:</p>
    <ul>
      <li ng-repeat="x    in names">
    	{{ x.name + ', ' + x.country }}
      </li>
    </ul>
    </div>
    
  5. Create a custom command

     <body ng-app="myApp">
     <runoob-directive></runoob-directive>
    
     <script>
     var app = angular.module("myApp", []);
     app.directive("runoobDirective", function() {
     	return {
     		template : "<h1>自定义指令!</h1>"
     	};
     });
     </script>
     </body>
    
  6. Scope:

     	<!DOCTYPE html>
     	<html>
     	<head>
     	<meta charset="utf-8">
     	<script src="https://cdn.staticfile.org/angular.js/1.4.6/angular.min.js"></script>
     	</head>
     	<body>
    
     	<div ng-app="myApp" ng-controller="myCtrl">
     		<input ng-model="name">
     		<h1>{{greeting}}</h1>
     		<button ng-click='sayHello()'>点我</button>	
     	</div>
    
     	<script>
     	var app = angular.module('myApp', []);
     	app.controller('myCtrl', function($scope) {
     		$scope.name = "Runoob";
     		$scope.sayHello = function() {
     			$scope.greeting = 'Hello ' + $scope.name + '!';
     		};
     	});
     	</script>
    
     	<p>当你修改输入框中的值时,会影响到模型(model),当然也会影响到控制器对应的属性值。</p>
    
     	</body>
     	</html>
     	
     	$rootScope 可作用于整个应用中。是各个 controller 中 scope 的桥梁。用 rootscope 定义的值,可以在各个 controller 中使用。
    
  7. the controller:

     <div ng-app="myApp" ng-controller="namesCtrl">
    
     <ul>
       <li ng-repeat="x in names">
     	{{ x.name + ', ' + x.country }}
       </li>
     </ul>
    
     </div>
     <script>
     	angular.module('myApp', []).controller('namesCtrl', function($scope) {
     		$scope.names = [
     			{name:'Jani',country:'Norway'},
     			{name:'Hege',country:'Sweden'},
     			{name:'Kai',country:'Denmark'}
     		];
     	});
     </script>
    
  8. filter:

    Comes with filter

     	<div ng-app="myApp" ng-controller="namesCtrl">
     		<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>
     	</div>
    

    Custom filters

     	var app = angular.module('myApp', []);
     	app.controller('myCtrl', function($scope) {
     		$scope.msg = "Runoob";
     	});
     	app.filter('reverse', function() { //可以注入依赖
     		return function(text) {
     			return text.split("").reverse().join("");
     		}
     	});
    
  9. $ Http service:

    Get get the requested data

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

    POST and GET method shorthand format:

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

    Request mode:

     $http.get, $http.head, $http.post, $http.put, $http.delete, $http.jsonp, $http.patch
    
  10. Timer:

    $timeout:

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

    $interval:

    var app = angular.module('myApp', []);
    app.controller('myCtrl', function($scope, $interval) {
    	$scope.theTime = new Date().toLocaleTimeString();
    	$interval(function () {
    		$scope.theTime = new Date().toLocaleTimeString();
    	}, 1000);
    })
    
  11. ng-options:
    drop-down menu:

    <div ng-app="myApp" ng-controller="myCtrl">
    	<select ng-init="selectedName = names[0]" ng-model="selectedName" ng-options="x for x in names"></select>
    </div>
    <script>
    	var app = angular.module('myApp', []);
    	app.controller('myCtrl', function($scope) {
    		$scope.names = ["Google", "Runoob", "Taobao"];
    	});
    </script>
    

    It can be an object:

    	<div ng-app="myApp" ng-controller="myCtrl">
    		<p>选择网站:</p>
    		<select ng-model="selectedSite" ng-options="x.site for x in sites"></select>
    		<h1>你选择的是: {{selectedSite.site}}</h1>
    		<p>网址为: {{selectedSite.url}}</p>
    	</div>
    	<script>
    		var app = angular.module('myApp', []);
    		app.controller('myCtrl', function($scope) {
    		   $scope.sites = [
    				{site : "Google", url : "http://www.google.com"},
    				{site : "Runoob", url : "http://www.runoob.com"},
    				{site : "Taobao", url : "http://www.taobao.com"}
    			];
    		});
    	</script>
    
  12. the disabled, the, show, hide-a

    ng-disabled: // exists but can not point

    	<div ng-app="" ng-init="mySwitch=true">
    		<p>
    			<button ng-disabled="mySwitch">点我!</button>
    		</p>
    		<p>
    			<input type="checkbox" ng-model="mySwitch">按钮
    		</p>
    		<p>{{ mySwitch }}</p>
    	</div>
    

    a-show:

    	<div ng-app="">
    		<p ng-show="true">我是可见的。</p>
    		<p ng-show="false">我是不可见的。</p>
    	</div>
    	
    	<div ng-app="" ng-init="hour=13">
    	<p ng-show="hour > 12">我是可见的。</p>
    

    of-hide:

    	<div ng-app="">
    		<p ng-hide="true">我是不可见的。</p>
    		<p ng-hide="false">我是可见的。</p>
    	</div>
    
  13. a click:

    <div ng-app="" ng-controller="myCtrl">
    	<button ng-click="count = count + 1">点我!</button>
    	<p>{{ count }}</p>
    </div>
    
  14. Create a module, add a controller

    Create a module:

    var app = angular.module("myApp", []);
    

    Add a controller:

    app.controller("myCtrl", function($scope) {
    	$scope.firstName	= "John";
    	$scope.lastName= "Doe";
    });
    
  15. service:

    <div ng-app="myApp" ng-controller="myCtrl">
    	<p>在获取数组 [255, 251, 200] 值时使用过滤器:</p>
    		<ul>
    		  <li ng-repeat="x in counts">{{x | myFormat}}</li>
    		</ul>
    	<p>过滤器使用服务将10进制转换为16进制。</p>
    </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);
    		};
    	}]);
    	app.controller('myCtrl', function($scope) {
    		$scope.counts = [255, 251, 200];
    	});
    </script>
    
  16. Form:

    Example 1:

    	<div ng-app="myApp" ng-controller="formCtrl">
    	// novalidate属性是在 HTML5 中新增的。禁用了使用浏览器的默认验证。
    	  <form novalidate>   
    		First Name:<br>
    		<input type="text" ng-model="user.firstName"><br>
    		Last Name:<br>
    		<input type="text" ng-model="user.lastName">
    		<br><br>
    		<button ng-click="reset()">RESET</button>
    	  </form>
    	  <p>form = {{user}}</p>
    	  <p>master = {{master}}</p>
    	</div>
    	<script>
    		var app = angular.module('myApp', []);
    		app.controller('formCtrl', function($scope) {
    			$scope.master = {firstName: "John", lastName: "Doe"};
    			$scope.reset = function() {
    				$scope.user = angular.copy($scope.master);
    			};
    			$scope.reset();
    		});
    	</script>
    

    Example Two:

    <!DOCTYPE html>
    	<html>
    	<script src="http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js"></script>
    	<body>
    	<h2>Validation Example</h2>
    	<form  ng-app="myApp"  ng-controller="validateCtrl"name="myForm" novalidate>
    		<p>用户名:<br>
    		  <input type="text" name="user" ng-model="user" required>
    		  <span style="color:red" ng-show="myForm.user.$dirty && myForm.user.$invalid">
    		  <span ng-show="myForm.user.$error.required">用户名是必须的。</span>
    		  </span>
    		</p>
    
    		<p>邮箱:<br>
    		  <input type="email" name="email" ng-model="email" required>
    		  <span style="color:red" ng-show="myForm.email.$dirty && myForm.email.$invalid">
    		  <span ng-show="myForm.email.$error.required">邮箱是必须的。</span>
    		  <span ng-show="myForm.email.$error.email">非法的邮箱。</span>
    		  </span>
    		</p>
    
    		<p>
    		  <input type="submit"
    		  ng-disabled="myForm.user.$dirty && myForm.user.$invalid ||
    		  myForm.email.$dirty && myForm.email.$invalid">
    		</p>
    	</form>
    	<script>
    		var app = angular.module('myApp', []);
    		app.controller('validateCtrl', function($scope) {
    			$scope.user = 'John Doe';
    			$scope.email = '[email protected]';
    		});
    	</script>
    	</body>
    	</html>
    

    Additional:

    			$dirty	表单有填写记录
    			$valid	字段内容合法的
    			$invalid	字段内容是非法的
    			$pristine	表单没有填写记录
    
  17. Global API:

    			API																	描述
    	angular.lowercase (<angular1.7)
    	angular.$$lowercase()(angular1.7+)			转换字符串为小写
    	angular.uppercase() (<angular1.7)
    	angular.$$uppercase()(angular1.7+)			转换字符串为大写
    	angular.isString()												判断给定的对象是否为字符串,如果是返回 true。
    	angular.isNumber()											判断给定的对象是否为数字,如果是返回 true。
    
  18. contain:

    runoob.htm file code:

    <h1>菜鸟教程</h1>
    <p>这是一个被包含的 HTML 页面,使用 ng-include 指令来实现!</p>
    

    include.html

    <body ng-app="">
    	<div ng-include="'runoob.htm'"></div>
    </body>
    
  19. ngAnimate

    ngAnimateYou can add or remove model class.
    ngAnimateModel does not make animate HTML elements, but ngAnimate will monitor the event, similar to the hidden HTML element is displayed, if the event occurs ngAnimateAnimation will use a predefined set of class to the HTML element.
    AngularJS add / remove class instruction:

    ng-show, ng-hide, ng-class, ng-view, ng-include, ng-repeat, ng-if, ng-switc
    

    ng-showAnd ng-hideinstructions for adding or removing ng-hide classvalues.
    Other add instruction class ng-enter into the DOM, remove DOM adds ng-leave property.
    When the HTML element position changes, ng-repeat instruction can also add ng-move type.
    Further, after completion, HTML element class set will be removed. For example: ng-hide instruction adds the following categories:

    ng-animate
    ng-hide-animate
    ng-hide-add (如果元素将被隐藏)
    ng-hide-remove (如果元素将显示)
    ng-hide-add-active (如果元素将隐藏)
    ng-hide-remove-active (如果元素将显示)
    
  20. AngularJS Routing:

    A simple example:

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="utf-8">
    <title>AngularJS 路由实例 - 菜鸟教程</title>
    <script src="https://cdn.bootcss.com/angular.js/1.7.0/angular.min.js"></script>
    <script src="https://cdn.bootcss.com/angular.js/1.7.0/angular-route.min.js"></script>
    </head>
    <body ng-app='routingDemoApp'>
     
    	<h2>AngularJS 路由应用</h2>
    	<ul>
    		<li><a href="#!/">首页</a></li>
    		<li><a href="#!/computers">电脑</a></li>
    		<li><a href="#!/printers">打印机</a></li>
    		<li><a href="#!/blabla">其他</a></li>
    	</ul>
    	 
    	<div ng-view></div>   // 内容显示位置
    	<script>
    		angular.module('routingDemoApp',['ngRoute'])
    		.config(['$routeProvider', function($routeProvider){
    			$routeProvider
    			.when('/',{template:'这是首页页面'})
    			.when('/computers',{template:'这是电脑分类页面'})
    			.when('/printers',{template:'这是打印机页面'})
    			.otherwise({redirectTo:'/'});
    		}]);
    	</script>
    </body>
    </html>
    

    Route settings object:

    	$routeProvider.when(url, {
    	template: string,    // 插入简单的 HTML 内容
    	templateUrl: string,   // 插入 HTML 模板文件如:'views/computers.html'
    	controller: string, function 或 array,  // function、string或数组类型,在当前模板上执行的controller函数,生成新的scope
    	controllerAs: string,  // string类型,为controller指定别名。
    	redirectTo: string, function,  // 重定向的地址。如: {redirectTo:'/'}
    	resolve: object<key, function>  // 指定当前controller所依赖的其他模块。
    });
    

    Example Two:

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="utf-8">
    <title>AngularJS 路由实例 - 菜鸟教程</title>
    <script src="https://cdn.bootcss.com/angular.js/1.7.0/angular.min.js"></script>
    <script src="https://cdn.bootcss.com/angular.js/1.7.0/angular-route.min.js"></script>
    <script type="text/javascript">
    angular.module('ngRouteExample', ['ngRoute'])
    .controller('HomeController', function ($scope, $route) { $scope.$route = $route;})
    .controller('AboutController', function ($scope, $route) { $scope.$route = $route;})
    .config(function ($routeProvider) {
    	$routeProvider.
    	when('/home', {
    		templateUrl: 'embedded.home.html',
    		controller: 'HomeController'
    	}).
    	when('/about', {
    		templateUrl: 'embedded.about.html',
    		controller: 'AboutController'
    	}).
    	otherwise({
    		redirectTo: '/home'
    	});
    });
    </script>
     
      
    </head>
     
    <body ng-app="ngRouteExample" class="ng-scope">
      <script type="text/ng-template" id="embedded.home.html">
    	  <h1> Home </h1>
      </script>
     
      <script type="text/ng-template" id="embedded.about.html">
    	  <h1> About </h1>
      </script>
     
      <div> 
    	<div id="navigation">  
    	  <a href="#!/home">Home</a>
    	  <a href="#!/about">About</a>
    	</div>
    	  
    	<div ng-view="">
    	</div>
      </div>
    </body>
    </html>
    
  21. Small summary:

    1) element contains AngularJS application (ng-app =).

    <div> 元素定义了 AngularJS 控制器的作用域 (ng-controller=)。在一个应用可以有很多控制器。
    

    2) AngularJS instructions:

    指令							描述
    ng-app					定义应用程序的根元素。
    ng-bind					绑定 HTML 元素到应用程序数据
    ng-bind-html			绑定 HTML 元素的 innerHTML 到应用程序数据,并移除 HTML 字符串中危险字符
    ng-bind-template		规定要使用模板替换的文本内容
    ng-blur					规定 blur 事件的行为
    ng-change				规定在内容改变时要执行的表达式
    ng-checked				规定元素是否被选中
    ng-class				指定 HTML 元素使用的 CSS 类
    ng-class-even			类似 ng-class,但只在偶数行起作用
    ng-class-odd			类似 ng-class,但只在奇数行起作用
    ng-click				定义元素被点击时的行为
    ng-cloak				在应用正要加载时防止其闪烁
    ng-controller			定义应用的控制器对象
    ng-copy					规定拷贝事件的行为
    ng-csp					修改内容的安全策略
    ng-cut					规定剪切事件的行为
    ng-dblclick				规定双击事件的行为
    ng-disabled				规定一个元素是否被禁用
    ng-focus				规定聚焦事件的行为
    ng-form					指定 HTML 表单继承控制器表单
    ng-hide					隐藏或显示 HTML 元素
    ng-href	为 				the <a> 元素指定链接
    ng-if					如果条件为 false 移除 HTML 元素
    ng-include				在应用中包含 HTML 文件
    ng-init					定义应用的初始化值
    ng-jq					定义应用必须使用到的库,如:jQuery
    ng-keydown				规定按下按键事件的行为
    ng-keypress				规定按下按键事件的行为
    ng-keyup				规定松开按键事件的行为
    ng-list					将文本转换为列表 (数组)
    ng-model				绑定 HTML 控制器的值到应用数据
    ng-model-options		规定如何更新模型
    ng-mousedown			规定按下鼠标按键时的行为
    ng-mouseenter			规定鼠标指针穿过元素时的行为
    ng-mouseleave			规定鼠标指针离开元素时的行为
    ng-mousemove			规定鼠标指针在指定的元素中移动时的行为
    ng-mouseover			规定鼠标指针位于元素上方时的行为
    ng-mouseup				规定当在元素上松开鼠标按钮时的行为
    ng-non-bindable			规定元素或子元素不能绑定数据
    ng-open					指定元素的 open 属性
    ng-options				在 <select> 列表中指定 <options>
    ng-paste				规定粘贴事件的行为
    ng-pluralize			根据本地化规则显示信息
    ng-readonly				指定元素的 readonly 属性
    ng-repeat				定义集合中每项数据的模板
    ng-selected				指定元素的 selected 属性
    ng-show					显示或隐藏 HTML 元素
    ng-src					指定 <img> 元素的 src 属性
    ng-srcset				指定 <img> 元素的 srcset 属性
    ng-style				指定元素的 style 属性
    ng-submit				规定 onsubmit 事件发生时执行的表达式
    ng-switch				规定显示或隐藏子元素的条件
    ng-transclude			规定填充的目标位置
    ng-value				规定 input 元素的值
    

    3) AngularJS events:

    ng-click, ng-dbl-click, ng-mousedown, ng-mouseenter, ng-mouseleave, ng-mousemove, ng-keydown, ng-keyup, ng-keypress, ng-change
    

    4) AngularJS validation properties:

    $dirty, $invalid, $erro
    

    5) AngularJS global API:

    	API							描述
    angular.lowercase()		将字符串转换为小写
    angular.uppercase()		将字符串转换为大写
    angular.copy()			数组或对象深度拷贝
    angular.forEach()		对象或数组的迭代函数
    

    6)JSON:

    	API						描述
    angular.fromJson()		反序列化 JSON 字符串
    angular.toJson()		列化JSON 字符串
    

Guess you like

Origin blog.csdn.net/qq_41433183/article/details/90769552