原:app.controller('secondController', function ($scope, $rootScope) {
$scope.name = '李四';
$rootScope.age = '30';
});
改:app.controller('firstController', ['$scope', function ($s) {……}]);
{{sex}}
var app = angular.module("myApp", []);
app.run(['$rootScope',function ($rootScope) {
$rootScope.sex = '男';
}]);
run方法初始化全局的数据,只对全局作用域起作用
var app = angular.module("myApp", []);
app.controller('secondController', function ($scope, $rootScope) {
$scope.name = '李四';
$rootScope.sex = '男';
});
作用:通知界面(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);
});
// 2s后“10”变成“20”
app.controller('firstController', function ($scope, $timeout) {
$scope.age = '10';
$timeout(function () {
$scope.age = '20';
},2000);
});
声明:
$scope.show = function () {
alert('李四');
$scope.name = '点击后的李四';
}
调用:
<div ng-controller="firstController" ng-click="show();">
{{name}}
div>
用于监听某个数值的变化(类似Android的TextWatcher)
//当总价>=100,运费为0;否则为¥10.
<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>