刚接触H5一个周,使用ionic+angularJS配合做webAPP和原生混合开发。可能以前着重点在iOS原生和C++方面,当初次接触前端技术,略微有点不适应。今天在做从网络获取数据展示到网页。第一次接触到控制器是在iOS原生上,而angularJS上的控制器比较抽象,搞了两天算是大体上会用,并没有完全理解。
angular.module('controllers',[])
首先是在module里面配置控制器,或者叫定义控制器。
angular.module('routes', []).config(function ($stateProvider, $urlRouterProvider) {
$stateProvider.state('list', {
url: '/list',
views: {
'main': {
templateUrl: 'templates/list.html',
controller: 'ListController'
}
}
})
.state('tab', {
url: "/tab",
abstract: true,
views:{
'main':{
templateUrl: "templates/tabs.html",
controller: "TabsController"
}
}
})
<pre style="font-family: Menlo; font-size: 9pt; background-color: rgb(255, 255, 255);">最后加一局默认跳转,就是在路由里面找不到跳转的时候,默认跳转到这个页面。
$urlRouterProvider.otherwise('/list') // 默认跳转
下面是做了左划右划的操作,用于切换tab页。
.controller('TabsController',function ($scope,$ionicTabsDelegate) {
$scope.onSwipeLift=function () {
if($ionicTabsDelegate.selectedIndex()!=4){
$ionicTabsDelegate.select($ionicTabsDelegate.selectedIndex()+1);
}
}
$scope.onSwipeRight=function () {
if($ionicTabsDelegate.selectedIndex()!=0){
$ionicTabsDelegate.select($ionicTabsDelegate.selectedIndex()-1);
}
}
})
这里的控制器是个抽象概念,我理解的是,控制器是一个包含页面中所有数据的一个抽象作用域,而$scope是在作用域里面数据和对数据的操作的总和。
.controller('PovertyFamilyListController', function ($scope, PovertyFamily,apiAddress) {
var currentIndex=0;//默认第一页
$scope.poorAdmassList=[];//群众数组
$scope.apiAddress=apiAddress;
//$scope.aasaaaa = apiAddress;
//上拉刷新
$scope.doRefresh = function () {
currentIndex=1;
PovertyFamily.povertyFamilyList(1, 10).success(function (response) {
$scope.poorAdmassList=response.datas;
})
.finally(function () {
$scope.$broadcast('scroll.refreshComplete');
})
}
//下拉无限滚动
$scope.loadMore = function() {
currentIndex++;
PovertyFamily.povertyFamilyList(currentIndex,10).success(function(response){
$scope.poorAdmassList=$scope.poorAdmassList.concat(response.datas);
$scope.$broadcast('scroll.infiniteScrollComplete');
})
};
})
这段代码是在控制器里面做操作,赋值,加载数据等等。原来angularJS是种弱语言,可以赋值的同时定义变量或者方法。比如
$scope.
apiAddress
=apiAddress;
apiaddress在$scope里面是没有这个属性的,但是在赋值的同时,定义了这个属性。还有就是赋值的类型,并不区分整型浮点型字符串。
在某个页面的控制器里获取到数据,并且赋值,就可以在该页面上展示数据,比如。
.controller('PersonalInfoController',function ($scope,$stateParams,PovertyFamily,poorAdmassId,apiAddress) {
poorAdmassId=$stateParams.id;
PovertyFamily.povertyFamilyPersonalData(poorAdmassId).success(function (response) {
$scope.personalInfo=response.data;
//$scope.aasaaaa = apiAddress;
})
})
上面代码是获取到数据,并把网络获取的数据赋值给页面上的personalinfo。这样在页面上就可以展示数据。
<h2>{{personalInfo.householderName}}(户主) <span class="list-span-sex-age-right">{{personalInfo.gender}} {{personalInfo.age}}岁 {{personalInfo.nationality}}</span></h2>
<p style="padding: 5px 0">浏览{{personalInfo.pV}}次 捐助总额{{personalInfo.salvationMoney}}元 被救助{{personalInfo.salvationCount}}次</p>