angularjs中不同controller之间的数据传递
在开发中我们经常遇到一个列表,列表后面有一个编辑按钮,当点击编辑按钮后弹出一个对话框,在对话框中对内容进行修改后提交到服务器,在angular js没有出来之前,我们的做法是使用ajax异步的方式进行请求,数据更改后使用jquery对dom元素进行修改。但是随着angular js的出现,我们不需要在操作这个dom.好了,废话少说 直接看代码
我们就针对一个列表进行一个编辑
@{
ViewBag.Title = "广告列表";
Layout = "~/Areas/Dashboard/Views/Shared/_Layout.cshtml";
}
@section header
{
<script src="~/Scripts/bootstrap-paginator.min.js"></script>
}
<div ng-app="featureApp">
<h2>广告列表</h2>
<div ng-controller="searchController">
<form class="form-inline">
<input type="text" class="input-small" ng-model="search.Title" id="searchTitle" style="width: 277px" placeholder="广告标题">
<select class="selectFilter" ng-model="search.isEnable" id="searchIsEnable" name="SelectedFilter" style="width: 78px">
<option value="true" selected="selected">显示</option>
<option value="false">隐藏</option>
</select>
<button class="btn" type="button" ng-click="SearchAd(search)">搜索</button>
</form>
</div>
<div ng-controller="featureController">
<table class="table table-hover">
<thead>
<tr>
<th>可见性</th>
<th>图片</th>
<th>广告类型</th>
<th>ItemType</th>
<th>Summary</th>
<th>标题</th>
<th>链接</th>
<th>开始时间</th>
<th>结束时间</th>
<th>编辑时间</th>
<th></th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in items ">
<td><input type="checkbox" ng-model="item.IsEnabled" disabled="disabled" /></td>
<td><img ng-src="item.Image" alt="广告图标" style="width: 32px; height: 32px;" /></td>
<td> {{item.AdType}} </td>
<td>{{item.ItemType}}</td>
<td> {{item.Summary}}</td>
<td> {{item.Title}}</td>
<td> {{item.LinkUri}}</td>
<td> {{item.StartTime}}</td>
<td> {{item.EndTime}}</td>
<td> {{item.CreateTime}}</td>
<td><button type="button" class="btn btn-primary" ng-click="editItem(item)">编辑</button></td>这里有一个点击编辑的事件,点击后主要是打开一个模态的对话框
</tr>
</tbody>
</table>
</div>
<div ng-controller="pageController">
<div>
<span>当前页码:{{currentPage+1}}</span><span>当前页码:{{dataservice.pageCount}}</span>
</div>
<div class="pagination pull-right">
<ul>
<li ng-class="{disabled: isFirst()}">
<a href="#" ng-click="prevPage()">« Prev</a>
</li>
<li ng-repeat="n in range( currentPage )"
ng-class="{active: n == currentPage}"
ng-click="setPage()">
<a href="#" ng-bind="n + 1">1</a>
</li>
<li ng-class="{disabled: isLast()}">
<a href="#" ng-click="nextPage()">Next »</a>
</li>
</ul>
</div>
</div>
<!-- 编辑列表项目对话框 -->
<div id="dlgEdit" title="编辑列表项目" ng-controller="dlgController">
<div>
<form class="form-horizontal">
<div class="control-group">
<label class="control-label" for="isEnabled">Is Enabled: </label>
<div class="controls">
<input type="checkbox" id="isEnabled" ng-model="item.IsEnabled" />
</div>
</div>
<div class="control-group">
<label class="control-label" for="imageAdress">图片: </label>
<div class="controls">
<img id="Image" title="Image" style="width: 60px; height: 60px;" ng-src="{{item.Image}}" />
<input type="text" id="imageAdress" ng-model="item.Image" />
</div>
</div>
<div class="control-group">
<label class="control-label" for="AdType">广告类型: </label>
<div class="controls">
<select ng-model="item.AdType" id="AdType">
<option value="Global_FullScreen">Global_FullScreen</option>
<option value="Lobby_Banner_Activity">Lobby_Banner_Activity</option>
<option value="Lobby_Banner_GiftPack">Lobby_Banner_GiftPack</option>
<option value="Lobby_Banner_Online" selected="selected">Lobby_Banner_Online</option>
<option value="Lobby_Banner_Single">Lobby_Banner_Single</option>
<option value="Video_FullScreen">Video_FullScreen</option>
</select>
</div>
</div>
<div class="control-group">
<label class="control-label" for="itemType">ItemType: </label>
<div class="controls">
<input type="text" id="itemType" placeholder="ItemType" ng-model="item.ItemType" />
</div>
</div>
<div class="control-group">
<label class="control-label" for="summary">Summary: </label>
<div class="controls">
<input type="text" id="summary" placeholder="Summary" ng-model="item.Summary" />
</div>
</div>
<div class="control-group">
<label class="control-label" for="title">标题: </label>
<div class="controls">
<input type="text" id="title" placeholder="标题" ng-model="item.Title" />
</div>
</div>
<div class="control-group">
<label class="control-label" for="linkuri">链接: </label>
<div class="controls">
<input type="text" id="linkuri" placeholder="链接" ng-model="item.LinkUri" />
</div>
</div>
<div class="control-group">
<label class="control-label" for="linkuri">应用id: </label>
<div class="controls">
<input type="text" id="linkuri" placeholder="应用id" ng-model="item.ItemId" />
</div>
</div>
<div class="control-group">
<label class="control-label" for="startTime">开始时间: </label>
<div class="controls">
<input type="text" id="startTime" placeholder="开始时间" ng-model="item.StartTime" />
</div>
</div>
<div class="control-group">
<label class="control-label" for="endTime">结束时间: </label>
<div class="controls">
<input type="text" id="endTime" placeholder="结束时间" ng-model="item.EndTime" />
</div>
</div>
<div class="control-group">
<label class="control-label" for="createTime">编辑时间: </label>
<div class="controls">
<input type="text" id="createTime" placeholder="编辑时间" ng-model="item.CreateTime" />
</div>
</div>
<div class="control-group">
<label></label>
<div class="controls">
<button type="button" ng-click="saveItem(item)">确定</button>当点击确定的时候,触发事件,把当前的item对象传过去
<button type="reset" ng-click="closeDialog()">关闭</button>
</div>
</div>
</form>
</div>
</div>
</div>
@section foot
{
//引入脚本
<script type="text/javascript" src="@Url.Content("~/Scripts/underscore-min.js")"></script>
<script type="text/javascript" src="@Url.Content("~/scripts/angular.min.js")"></script>
<script type="text/javascript">
// 应用
var app = angular.module('featureApp', []);
// 应用中的服务
app.factory("dataService", [
'$http', function ($http) {
var service = {};
// 数据的页码(页面下面现在的 123.....等数字)
service.totalCount = [];
//总页数
service.pageCount = 0;
//总条数
service.dataCount = 0;
// 当前的数据
service.currentItems = [];
// 当前的单条数据
service.currentItem = {};
service.editItem = {};
// 当前的页码
service.pageIndex = 0;
// 默认的启用状态
service.isEnable = true;
service.title = "";
// 获取数据的方法
service.getData = function (pageIndex, isEnable, title, callback) {
// 取数据
var parameter = { pageIndex: pageIndex, isEnable: isEnable, Title: title };
$http.post("/Advertisement/List", parameter)
.success(function (data) {
service.currentItems.length = 0;
//如果这里你直接赋值 service.currentItems=data,那么页面会不会显示数据,为什么呢,angular在判断一个数据是否更新的依据是,新对象和旧对象进行比较,如果你只对一个集合赋值,那么它只会更新集合的第一个元素,所
//以要用一个遍历进行赋值
for (var i = 0; i < data.length; i++) {
service.currentItems.push(data[i]);
}
service.pageIndex = pageIndex;
service.isEnable = isEnable;
service.title = title;
if (callback) {
callback(service.currentItems);
}
})
.error(function () {
console.error("数据读取错误!");
});
// 取总数
service.getDataCount(isEnable, title);
};
//根据不同的条件取得数据的数量(总页数,总条数)
service.getDataCount = function (isEnable, title) {
$http.post("/Advertisement/AdCount", { isEnable: isEnable, Title: title })
.success(function (count) {
//注意,在angular中要想清空一个列表就必须使用.length=0
service.totalCount.length = 0;
var pageCount = Math.ceil(count.itemCount / 1);
//这里不能直接写service.totalCount=count.itemCount
for (var i = 0; i < pageCount; i++) {
service.totalCount.push(i);
}
service.dataCount = count.itemCount;
service.currentPage = 0;
service.pageCount = pageCount;
})
.error(function () {
console.error("get item count error.");
});
};
//点击对话框的确定方法后,我们把数据回传到服务器进行更新
service.updateItem = function (item, callback) {
$http.post("/Advertisement/UpdaAd", item)
.success(function (data) {
angular.extend(service.currentItem, item);
callback();
})
.error(function () {
alert("保存错误!");
});
};
return service;
}
]);
app.controller('featureController', function ($scope, $http, dataService) {
dataService.getData(0, true, '', function (items) {
$scope.items = items;
});
//点击编辑时弹出对话框,当然如果用户在弹出的框里做了操作而没有保存,那么列表的数据也会跟着改变
//为了防止这中情况我们使用了angular的扩展,最初使用copy,发现对象没有更新,所有使用了extend
$scope.editItem = function (item) {
dataService.currentItem = item;
angular.extend(dataService.editItem, item);
$("#dlgEdit").dialog("open");
};
var option = {
modal: true, // 创建模式对话框
autoOpen: false, // 只初始化,不显示
width: 800
};
$("#dlgEdit").dialog(option);
$("#startTime").datepicker();
$("#endTime").datepicker();
});
app.controller('pageController', function ($scope, $http, dataService) {
$scope.dataservice = dataService;
//$scope.pageSize = 1;
$scope.currentPage = 0;
$scope.dataservice.pageCount = $scope.dataservice.pageCount;
$scope.dataservice.itemCount = $scope.dataservice.dataCount;
$scope.pagedItems = [];
//上一页
$scope.prevPage = function () {
if (!$scope.isFirst()) {
$scope.currentPage -= 10;
}
};
// 下一页
$scope.nextPage = function () {
if (!$scope.isLast()) {
$scope.currentPage += 10;
if ($scope.currentPage >= $scope.pagedItems.length)
$scope.currentPage = $scope.pagedItems.length - 1;
}
};
$scope.isFirst = function () {
var currentSegment = Math.floor($scope.currentPage / 10);
return currentSegment == 0;
};
$scope.isLast = function () {
var currentSegment = Math.floor($scope.currentPage / 10);
var maxSegment = Math.ceil($scope.pagedItems.length / 10 - 1);
return currentSegment == maxSegment;
};
// 直接设置特定页
$scope.setPage = function () {
console.info("Set Page to " + this.n);
$scope.currentPage = this.n;
dataService.getData(this.n, $("#searchIsEnable option:selected").val(), $("#searchTitle").val(), function (items) {
});
};
// 返回当前显示页码的数组
$scope.range = function (current) {
var start = Math.floor(current / 10) * 10;
var end = start + 10;
if (end > $scope.pagedItems.length)
end = $scope.pagedItems.length;
var ret = [];
for (var j = start; j < end; j++) {
ret.push(j);
}
return ret;
};
$scope.pagedItems = $scope.dataservice.totalCount;
});
app.controller('dlgController', function ($scope, $http, dataService) {
$scope.item = dataService.editItem;
$scope.saveItem = function (item) {
dataService.updateItem(item, function () {
$("#dlgEdit").dialog("close");
});
};
$scope.closeDialog = function () {
$("#dlgEdit").dialog("close");
};
});
app.controller('searchController', function ($scope, $http, dataService) {
$scope.search = { isEnable: true, Title: "" };
$scope.SearchAd = function (search) {
dataService.getData(0, search.isEnable, search.Title, function (item) {
console.info("search ok."+item);
});
};
});
</script>
}
最后写一下几点注意的事项,如果要想保住数据的同步,所有的操作必须针对一个对象,比如我们操作列表的数据,列表会去调用getData方法,getData方法有一个回调函数,这个回调函数返回了一个服务的对象,而我们这个服务的对象是绑定在列表上的。
浙公网安备 33010602011771号