Angularjs记录

controller间通信


在填web坑的时候遇到这样的需求
主要是通过$broadcast实现
检索到的一个例子如下,很容易改造成需要的样子

html

<div ng-controller="ControllerZero">
     <input ng-model="message" >
    <button ng-click="handleClick(message);">LOG</button>
</div>

<div ng-controller="ControllerOne">
   <input ng-model="message" >
</div>

<div ng-controller="ControllerTwo">
    <input ng-model="message" >
</div>

js部分

var myModule = angular.module('myModule', []);
myModule.factory('mySharedService', function($rootScope) {
    var sharedService = {};
    
    sharedService.message = '';

    sharedService.prepForBroadcast = function(msg) {
        this.message = msg;
        this.broadcastItem();
    };

    sharedService.broadcastItem = function() {
        $rootScope.$broadcast('handleBroadcast');
    };

    return sharedService;
});

function ControllerZero($scope, sharedService) {
    $scope.handleClick = function(msg) {
        sharedService.prepForBroadcast(msg);
    };
        
    $scope.$on('handleBroadcast', function() {
        $scope.message = sharedService.message;
    });        
}

function ControllerOne($scope, sharedService) {
    $scope.$on('handleBroadcast', function() {
        $scope.message = 'ONE: ' + sharedService.message;
    });        
}

function ControllerTwo($scope, sharedService) {
    $scope.$on('handleBroadcast', function() {
        $scope.message = 'TWO: ' + sharedService.message;
    });
}

ControllerZero.$inject = ['$scope', 'mySharedService'];        
        
ControllerOne.$inject = ['$scope', 'mySharedService'];

ControllerTwo.$inject = ['$scope', 'mySharedService'];

浅显易懂,不做过多解释了
如果msg直接传递了$scope下的对象,由于对象引用问题,会有“牵一发而动全身的效果”
比如编辑用户信息这个面板的数据通过通信从标题栏所属的controller传递过来,就会导致编辑面板的改动即时展现在了标题栏=。=
事实上想要从外部修改一个controller里的scope,可以通过angular.element().scope()来获取。


angular2中从外部更新数据

angular2中采用了组件化的形式,scope的方法已经被取代
从外部更新数据可以采用以下形式

//our root app component
import {Component, NgZone} from 'angular2/core'
@Component({  
  selector: 'my-app',  
  template: `<div>      
    <h2>Hello {{name}}</h2>    
  </div>`
})
export class App {  
        constructor(zone: NgZone) {   
               this.name = 'Angular2'    
               window.app = this   
               window.zoneImpl = zone  
        }
}

然后外部使用

zoneImpl.run(() => window.app.name = "new name!")

零零碎碎


加载时的闪烁问题采用ng-cloak解决

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容