Angularjs記錄

controller間通信


在填web坑的時(shí)候遇到這樣的需求
主要是通過(guò)$broadcast實(shí)現(xiàn)
檢索到的一個(gè)例子如下,很容易改造成需要的樣子

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'];

淺顯易懂,不做過(guò)多解釋了
如果msg直接傳遞了$scope下的對(duì)象,由于對(duì)象引用問(wèn)題,會(huì)有“牽一發(fā)而動(dòng)全身的效果”
比如編輯用戶信息這個(gè)面板的數(shù)據(jù)通過(guò)通信從標(biāo)題欄所屬的controller傳遞過(guò)來(lái),就會(huì)導(dǎo)致編輯面板的改動(dòng)即時(shí)展現(xiàn)在了標(biāo)題欄=。=
事實(shí)上想要從外部修改一個(gè)controller里的scope,可以通過(guò)angular.element().scope()來(lái)獲取。


angular2中從外部更新數(shù)據(jù)

angular2中采用了組件化的形式,scope的方法已經(jīng)被取代
從外部更新數(shù)據(jù)可以采用以下形式

//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!")

零零碎碎


加載時(shí)的閃爍問(wèn)題采用ng-cloak解決

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容