1 $scope(作用于一个Controller)与$rootScope(全局)的作用域区别
2 特殊变量名(如:$scope,$rootScope)在js压缩(类似Android的代码混淆)过程中避免被替换而报错的解决方案
原:app.controller('secondController',function ($scope,$rootScope) {
$scope.name = '李四';
$rootScope.age = '30';
});
改:app.controller('firstController',['$scope',function ($s) {……}]);
3 无controller的数据进行绑定
3.1 方案1:app.run()
{{sex}}
var app = angular.module("myApp",[]);
app.run(['$rootScope',function ($rootScope) {
$rootScope.sex = '男';
}]);
3.2 方案2:直接在其他controller中使用$rootScope
run方法初始化全局的数据,只对全局作用域起作用
var app = angular.module("myApp",[]);
app.controller('secondController',function ($scope,$rootScope) {
$scope.name = '李四';
$rootScope.sex = '男';
});
4 $scope中的$apply、$timeout、$watch方法
4.1 $apply
作用:通知界面(View)数据(Model)的变化(类似Android中列表控件的notifyDataChanged())
// 2s后“张三”变成“李四”
var app = angular.module("myApp",[]);
app.controller('firstController',function ($scope) {
$scope.name = '张三';
setTimeout(function () {
$scope.$apply(function () {
$scope.name = '李四';
});
},2000);
});
4.2 timeout的另一种用法:
// 2s后“10”变成“20”
app.controller('firstController',$timeout) {
$scope.age = '10';
$timeout(function () {
$scope.age = '20';
},2000);
});
4.3 ng-click=”show();”的使用
声明:
$scope.show = function () {
alert('李四');
$scope.name = '点击后的李四';
}
调用:
<div ng-controller="firstController" ng-click="show();"> {{name}} </div>
4.3 $watch
用于监听某个数值的变化(类似Android的TextWatcher)
//当总价>=100,运费为0;否则为¥10. <!DOCTYPE html> <html> <head> <Meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title></title> <script type="text/javascript" src="../lib/angular.min.js"></script> </head> <body> <div ng-app="myApp"> <div ng-controller="CartController"> <p>价格:<input type="number" ng-model="iphone.money"></p> <p>个数:<input type="number" ng-model="iphone.num"></p> <p>费用:<span>{{ sum() | currency:'¥' }}</span></p> <p>运费:<span>{{iphone.fre | currency:'¥'}}</span></p> <p>总额:<span>{{ sum() + iphone.fre | currency:'¥'}}</span></p> </div> </div> <script type="text/javascript"> var app = angular.module("myApp",[]); app.controller('CartController',function ($scope) { $scope.iphone = { money: 5,num: 1,fre: 10 }; $scope.sum = function () { return $scope.iphone.money * $scope.iphone.num; }; //当总价>=100,运费为0;否则为¥10. $scope.$watch($scope.sum,function (newVal,oldVal) { console.log("newVal = " + newVal); console.log("oldVal = " + oldVal); $scope.iphone.fre = newVal >= 100 ? 0 : 10; }); }); </script> </body> </html>