Bright Leopold

i come from the other world,i will go back after the love,the regret,the alive and the dead are over

导航

controller共享数据

刚开始使用angularjs,能感受到他的强大,也在学习的途中遇到一些问题

一般我们在angularjs中共享数据使用DI的方法,具体代码如下:

<script>
angular.module('myApp.service',[])
.factory('myService', function () {
var arr=[];
return{
add: function () {
arr.push(1);
},
data:arr
};
});
var myApp=angular.module('myApp',["myApp.service","myApp.filter"]);
myApp.controller('myController1', function ($scope,myService) {
$scope.hi=myService.data;
$scope.add= function () {
myService.add();
}
})
.controller('myController2', function ($scope,myService) {
$scope.hi=myService.data;
});
</script>

 

这样使用有一个问题,从服务返回的对象只能绑定对象实现双向绑定,如果使用返回对象的属性进行绑定就会出现绑定不上的问题.如下

controller('myController2', function ($scope,myService) {
$scope.hi=myService.data.length;
});

这个时候,如果希望绑定返回对象的属性值得时候该怎么做呢,我想到了使用自定义过滤器的方法解决.

如下面的列子,我希望能双向绑定数组对象的长度属性.

<script>
angular.module('myApp.service',[])
.factory('myService', function () {
var arr=[];
var obj={lg:0};
return{
add: function () {
arr.push(1);
obj.lg+=1;
},
data:arr,
KK:obj
};
});
angular.module('myApp.filter',[])
.filter('capitalize', function () {
return function (input) {
if(input){
return input.lg;
}
}
});
var myApp=angular.module('myApp',["myApp.service","myApp.filter"]);
myApp.controller('myController1', function ($scope,myService) {
$scope.hi=myService.data;
$scope.add= function () {
myService.add();
}
})
.controller('myController2', function ($scope,myService) {
$scope.hi=myService.KK;
});
</script>

当界面绑定数据的时候进行过滤,就可以得到想要的结果

posted on 2015-03-25 23:28  Bright Leopold  阅读(572)  评论(0编辑  收藏  举报