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解決

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容