zoukankan      html  css  js  c++  java
  • angularjs 中使用 service 在controller 之间 share 对象和数据

    文章来自:http://www.cnblogs.com/slardar1978/p/4203822.html

    在做angularjs 的UI 时,我们经常会遇到一个页面之间有几个controller,在controller 之间share 公共的一些数据和方法就变得比较困难,目前推荐的做法是创建一个service, 在service 中存储公共的数据,然后把service 注入到controller中来达到share 数据的目的。

    下面是最简单的一个sample 列子

    angularjs 模板页面, 有userContoller 和 customerController,我们将在这两个controller 之间共享数据, 具体定义如下:

    复制代码
    <div ng-app="APP">
        <h2>angularjs sample</h2>
        <div ng-controller="userController">        
            <div>{{golbal_sitename}}</div>
            <div>{{controllerName}}</div>
            <div><button ng-click="sayHello()">sayHello</button></div>
        </div>
        <hr />
         <div ng-controller="customerController">        
            <div>{{golbal_sitename}}</div>
             <div>{{controllerName}}</div>
             <div><button ng-click="sayHello()">sayHello</button></div>
        </div>
    </div>
    复制代码

    angularjs js 页面, 在这个代码中我们定义了 module APP, userController 和customerController, 另外我们还定义了一个service, dataService,这个service 包含需要共享的数据和方法,在这里我们返回了一个属性golbal_sitename, 和 一个sayHello 方法。

    然后,在声明controller 的时候,我们把dataservice 这个对象分别注入到userController 和customerController,注入完成后,我们就可以在controller 的代码中访问dataService共享的数据了。

    复制代码
    var APP = angular.module('APP',[]).
    controller('userController', ['$scope','dataService',function($scope,dataService) {
           $scope.controllerName='userController';
           $scope.golbal_sitename=dataService.golbal_sitename;
           $scope.sayHello =function(){
               dataService.sayHello($scope.controllerName);
           }
    }]).
    controller('customerController',['$scope','dataService', function($scope,dataService) {
           $scope.controllerName='customerController';
           $scope.golbal_sitename=dataService.golbal_sitename;
           $scope.sayHello =function(){
               dataService.sayHello($scope.controllerName);
           }
    }]).
    factory('dataService',function(){
        return {
            golbal_sitename:"this is the shared value",
            sayHello:function(msg){
                alert(msg);
            }
        }
    });
    复制代码

    最后的结果截图如下:

    从图中我们可以看到

    ”this is the shared value“ 值来自dataService
    sayHello 的具体实现也是在dataService中定义的。
     
    这样我们就实现了在controller 之间共享对象。
     
  • 相关阅读:
    [King.yue]EXT.Grid行双击事件
    [King.yue]关于代码调试时的缓存问题的一个解决办法
    [Buffalo]ASP.NET MVC路由映射
    [Tommas] 如何创建自动化功能测试的基本原则
    [Tommas] Web测试中,各类web控件测试点总结
    [Tommas] ERP系统测试用例设计1(转)
    [King.yue]VS2012 无法启动IIS Express Web服务器的解决方案
    原创 html动态表格
    原创 SqlParameter 事务 批量数据插入
    jquery readio checked
  • 原文地址:https://www.cnblogs.com/Uncle-Maize/p/6291951.html
Copyright © 2011-2022 走看看