.state(‘producers’, {
url: ‘/producers’,
templateUrl: ‘views/producers.html’,
controller: ‘ProducersCtrl’
})
.state(‘producer’, {
url: ‘/producer/:producerId’,
templateUrl: ‘views/producer.html’,
controller: ‘ProducerCtrl’
})
(2) 在producers.html中,定义点击事件,比如ng-click=”toProducer(producerId)”,在ProducersCtrl中,定义页面跳转函数 (使用ui-router的$state.go接口):
.controller(‘ProducersCtrl’, function ( scope, state) {
scope.toProducer = function (producerId) {state.go(‘producer’, {producerId: producerId});
};
});
(3) 在ProducerCtrl中,通过ui-router的$stateParams获取参数producerId,譬如:
.controller(‘ProducerCtrl’, function ( scope, state, stateParams) {
var producerId =stateParams.producerId;
});
.factory(‘myFactory’, function () {
//定义factory返回对象
var myServices = {};
//定义参数对象
var myObject = {};
/**
* 定义传递数据的set函数
* @param {type} xxx
* @returns {*}
* @private
*/
var _set = function (data) {
myObject = data;
};
/**
* 定义获取数据的get函数
* @param {type} xxx
* @returns {*}
* @private
*/
var _get = function () {
return myObject;
};
// Public APIs
myServices.set = _set;
myServices.get = _get;
// 在controller中通过调set()和get()方法可实现提交或获取参数的功能
return myServices;
});
.factory(‘addressFactory’, [‘ rootScope′,function( rootScope) {
// 定义所要返回的地址对象
var address = {};
// 定义components数组,数组包括街道,城市,国家等
address.components = [];
// 定义更新地址函数,通过$rootScope.$broadcast()设置全局事件'AddressUpdated'
// 所有子作用域都能监听到该事件
address.updateAddress = function (value) {
this.components = value.slice();
$rootScope.$broadcast('AddressUpdated');
};
// 返回地址对象
return address;
}]);
(2) 在获取地址的controller中:
// 动态获取地址,接口方法省略
var component = {
addressLongName: xxxx,
addressShortName: xxxx,
cityLongName: xxxx,
cityShortName: xxxx
};
// 定义地址数组
$scope.components = [];
scope. watch(‘components’, function () {
// 将component对象推入$scope.components数组
components.push(component);
// 更新addressFactory中的components
addressFactory.updateAddress(components);
});
(3) 在监听地址变化的controller中:
// 通过addressFactory中定义的全局事件’AddressUpdated’监听地址变化
scope. on(‘AddressUpdated’, function () {
// 监听地址变化并获取相应数据
var street = address.components[0].addressLongName;
var city = address.components[0].cityLongName;
// 通过获取的地址数据可以做相关操作,譬如获取该地址周边的商铺,下面代码为本人虚构
shopFactory.getShops(street, city).then(function (data) {
if(data.status === 200){
scope.shops = data.shops;
}else{log.error(‘对不起,获取该位置周边商铺数据出错: ‘, data);
}
});
});
// 定义并初始化localStorage中的counter属性
scope. storage = localStorage. default({
counter: 0
});
// 假设某个factory(此例暂且命名为counterFactory)中的updateCounter()方法
// 可以用于更新参数counter
counterFactory.updateCounter().then(function (data) {
// 将新的counter值上传到localStorage中
scope. storage.counter = data.counter;
});
(2) 监听localStorage中的参数变化 - Controller B
scope.counter= localStorage.counter;
scope. watch(‘counter’, function(newVal, oldVal) {
// 监听变化,并获取参数的最新值
$log.log(‘newVal: ‘, newVal);
});