Angularjs记录

controller间通信


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

html

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: `

Hello {{name}}

` }) export class App { constructor(zone: NgZone) { this.name = 'Angular2' window.app = this window.zoneImpl = zone } }

然后外部使用

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

零零碎碎


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

你可能感兴趣的:(Angularjs记录)