zoukankan      html  css  js  c++  java
  • 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>

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

  • 相关阅读:
    SQL SERVER备份数据库存储过程.
    JMail组件使用中文文档
    Oracle,SQL Server,Access万能数据库通用类!
    快速幂的理解及使用
    关于地图坐标问题转换
    ref和依赖注入
    Unity3D 中的程序后台运行
    Unity中创建双面材质
    Unity3d 移动平台中文显示问题
    Unity3D 4.0中使用传统动画
  • 原文地址:https://www.cnblogs.com/weichao975/p/4367375.html
Copyright © 2011-2022 走看看