$watch实现对$scope中挂载的数据监听
//参数1 是你将要监听的属性,且要单引号括起来。
//参数2 是一个回调函数,函数的参数是改变的新值和旧值
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="lib/angular.js"></script>
</head>
<body>
<div ng-app="app">
<div ng-controller="MainController">
<input type="text" ng-model="msg">
<p>{{msg}}</p>
</div>
</div>
<script>
var app= angular.module('app',[])
app.controller('MainController',function($scope){
$scope.msg="hello world"
//$watch实现对$scope中挂载的数据监听
//参数1是你将要监听的属性,且要单引号括起来。
//参数2是一个回调函数,函数的参数是改变的新值和旧值
$scope.$watch('msg',function(newvalue,ordvalue){
console.log('newvalue:'+newvalue+'ordvalue:'+ordvalue)
})
})
</script>
</body>
</html>
02-$apply实现脏检查机制
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="lib/angular.js"></script>
</head>
<body>
<div ng-app="app">
<div ng-controller="MainController">
<input type="text" ng-model="num">
<input type="button" value="add1" onclick="add()">
</div>
</div>
<script>
var app = angular.module('app', [])
//使用推断式注入声明,但是參數會被混淆變,压缩时
//并會替代為a,b之類,这时我们推荐行内式注入式声明
app.controller('MainController', function ($scope) {
$scope.num = 0
//通过全局对象window来获取$scope的引用,则这个属性获得同样功能
window.scope = $scope
})
//创建普通的JavaScript的函数
function add() {
window.scope.num += 1
//手动调用&apply,实现脏检查机制
//在angular中$apply是自动执行,无需手动调用
window.scope.$apply()
console.log(window.scope.num)
}
// var app = angular.module('myApp', []);
// 创建 value 对象 "temp" 并传递数据
// app.value("temp", "Hello");
// app.controller('MyController', ['$scope', 'temp', function ($scope, temp) {
// $scope.sayHello = function () {
// alert(temp);
// }
// }]);
</script>
</body>
</html>
依赖注入方式
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="lib/angular.js"></script>
</head>
<body>
<div ng-app="app">
<div ng-controller="MainController">
<input type="button" value="点我" ng-click="sayHello()">
</div>
</div>
<script>
var app=angular.module('app',[])
app.value('temp','hello')
// 行内式注入声明
// //创建value对象“temp”并传递数据
// app.value('temp','hello')
// app.controller('MainController',['$scope','temp',function($scope,temp){
// $scope.sayHello=function(){
// alert(temp)
// }
// }])
//显示注入声明
var MainController=function($scope,temp){
$scope.sayHello=function(){
alert(temp)
}
}
MainController.$inject=['$scope','temp']
app.controller('MainController',MainController)
</script>
</body>
</html>