Angular: Empty Fiddle
http://angularjs.org/
HTML
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.1/angular.min.js"></script>
<div ng-controller="mainCtrl as main">
<input ng-model="main.topicsInput" ng-change="main.updateList()"/>
<my-directive topics="main.topicList" update-on="some.event"></my-directive>
<my-directive topics="main.staticTopicList"></my-directive>
<my-directive topics="main.topicList" update-on="some.event"></my-directive>
</div>
JavaScript
var myApp = angular.module('myApp', []);
//this is the main controller which provides the topics I need to search for..
myApp.controller("mainCtrl", ["$scope", function ($scope) {
var vm = this;
vm.topicsInput = "";
vm.topicList = [];
vm.staticTopicList = ["foo", "bar"];
vm.updateList = function() {
//this is the actual array of topics I need in the directive
vm.topicList = vm.topicsInput.trim().split(" ");
//this is a broadcast I could send..
$scope.$broadcast("some.event", vm.topicList);
}
}]);
//I have around 10 directives like this one,
//each one should be usable alone separately from the others
//each represents different datasets depending on the "topics" argument
//some does not need updating after initialisation (topics are fixed)
myApp.directive('myDirective', function () {
//the controller uses the servcie to fetch teh required data
var ctrlFn = function ($scope, myService) {
$scope.fetchData = function (topics) {
myService.get({ "topics": topics }, function (data) {
$scope.drawData(data);
});
};
//would it be better to make all directives listen to the broadcast
if ($scope.updateOn) {
$scope.$on($scope.updateOn, function (ev, tags) {
$scope.fetchData(tags);
});
}
//or simply make them watch their topics?
$scope.$watch("topics", function (theTopics) {
//$scope.fetchData(theTopics);
});
};
var linkFn = function (scope, element) {
scope.drawData = function (data) {
//redraw element using new data
element.html(data)
}
//init, not needed if we use $watch
scope.fetchData(scope.topics)
};
return {
scope: {
topics: "=",
updateOn: "@"
},
restrict: "AE",
replace: true,
link: linkFn,
...