2016-11-09 50 views
1

我正在嘗試做一些簡單的事情。Angular 1.5非父組件到組件通信

我有一個名爲發件人的組件,想要發送消息給一個名爲receiver的非子組件。發件人找到接收器組件並更改其屬性值。

不幸的是,接收器組件不能識別它的屬性是否已經改變。

完成此操作後,會有多個發送組件使用相同的接收組件實例,因此我不想將其設置爲子組件。

如何讓接收組件識別出它具有新的屬性值?

這裏有一個plunkr

HTML:

<!DOCTYPE html> 
<html> 
    <head> 
    <script data-require="[email protected]" data-semver="1.5.8" 
      src="https://code.angularjs.org/1.5.8/angular.js"></script> 
    <link rel="stylesheet" href="style.css" /> 
    <script src="https://code.angularjs.org/1.5.8/angular.js"></script> 
    </head> 
    <body> 
    <h1>Test sending values to a component from a non-parent component</h1> 
    <sender id="SendingComponent"></sender> 
    <h2>past send tag</h2> 
    <receiver id="ToComponent" textvalue="defaultvalue"></receiver> 
    <h2>Past receiver tag</h2> 
    <script src="script.js"></script> 
    </body> 
</html> 

的Javascript:

var app = angular.module('app',[]) 
    .component("sender", { 
    template: "<div> I send messages to receiver. 
     Receiver should say 'a new sent value'.</div>", 
    controller: [function() { 
     var ctrl = this; 
     ctrl.$oninit = function() { 
     var receiver = document.getElementById('ToComponent'); 
     receiver.attributes.setNamedItem('textvalue', 'a new sent value'); 
     $timeout(function() { $scope.apply();}); 
    }; 
    }]}) 
    .component("receiver", { 
    template: '<div>I received this message: 
     {{receiverCtrl.textvalue}}</div>', 
    bindings: { 
     textvalue: '<' // using '@' makes the default value work, 
         // but is described as a one time bind 
    }, 
    controllerAs: 'receiverCtrl', 
    controller: [function() { 
     var ctrl = this; 
     ctrl.$onChanges = function (changesObj) { 
     if (changesObj.textvalue !== undefined) { 
      ctrl.textvalue = changesObj.textvalue.currentValue; 
     } 
     } 
    }] 
}); 

angular.bootstrap(document, ['app']); 

回答

1

聽起來像你對我應該事件工作來代替。也許你的發送者會改變價值,你的接收者會聽到這個事件,並且做任何需要做的事情。

這也有你的發件人不需要操縱DOM發送他們的消息的優勢。這樣,如果有必要,您只會將DOM操作留給接收者。

+0

解決了這個問題。我選擇了$ rootscope。$ broadcast,因爲組件可能位於完全實現的版本中。 在閱讀本主題時,我發現了對這個github代碼的引用,這可能會更有效率(根據我追蹤的原始評論)。還沒有驗證,但這裏的鏈接:https://github.com/georapbox/angular-PubSub –