<div ng-app="myApp">
<a href="#/index">首页</a>
<a href="#/lst">商品列表</a>
<div ng-view></div>
</div>
<script type="text/javascript">
var app = angular.module('myApp', ['ngRoute']);
app.run(function ($rootScope) {
$rootScope.goods = [{
id: 1,
tit: '商品一',
price: 100 // 瓣增了一个表示商品单价的字段
}, {
id: 2,
tit: '商品二',
price: 150
}];
});
app.config(function ($routeProvider) {
$routeProvider.when('/index', {
template: '<div>这是index模板{{data}}</div><div ng-bind="author"></div>',
controller:'ctrlIndex'
}).when('/lst', {
template: '<ul><li ng-repeat="item in goods"><a href="#/detail/{{item.id}}">{{item.tit}}</a></li></ul>',
controller:'ctrlLst'
}).when('/detail/:id', {
templateUrl: 'detail.html',
controller: 'ctrlDetail'
}).otherwise({
redirectTo: '/index'
});
});
app.controller('ctrlIndex', function ($scope) {
$scope.data = 'Hello';
$scope.author = 'CYF';
});
app.controller('ctrlLst', function ($scope) {
});
app.controller('ctrlDetail', function ($rootScope, $routeParams, $scope, $location) {
var id = $routeParams.id;
var detail = $rootScope.goods.find(function (item) {
return item.id == id;
});
$scope.id = id;
$scope.tit = detail.tit;
$scope.price = detail.price;
$scope.selectedNum = 1;
// 选中的数量
// 计算总价的方法
$scope.sum = function () {
return $scope.price * $scope.selectedNum;
};
// 监听计算总价的方法的返回值
$scope.$watch($scope.sum, function (newVal) {
$scope.ship = newVal >= 300 ? 0 : 10; // 计算运费
});
$scope.btnClick = function () {
var all = $scope.sum();
if (all >= 500) {
$location.path('/index'); // 跳转到指定页
} else {
$location.path('/lst').replace();// 使用 replace() 可使在跳转网页时不会保存到历史记录
}
};
});
</script>