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>

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

  • 相关阅读:
    11.关于django的content_type表
    6.re正则表达式
    1.关于python 的hmac加密
    4.瀑布流js
    10.django的一些方法理解
    7.一些比较有用的网站
    准备辞职了,走之前想解决的问题ptr 为空
    Oracle 代码生成小工具免费下载
    Js 中一个判断类型的方法
    jQuery 加上最后自己的验证
  • 原文地址:https://www.cnblogs.com/weichao975/p/4367375.html
Copyright © 2011-2022 走看看