Himmators
Himmators

Reputation: 15006

What do I need to do to get $broadcast running?

I have been working with the excelent ngStorage plugin for angular.

When setting it up you can declare a $scope-node connected to the localstorage like this:

$scope.$store = $localStorage;

$scope.$store is now accessible in all controllers etc.

I want to remove some stuff from localstorage and access it using broadcast instead.

In my init I performed:

$scope.taskarr = [];
$rootScope.$broadcast('taskarrbroad',$scope.taskarr);

What is required in order to add, remove and $watch this array, none of the mentioned seem to work.

Here, nothing happens

controller('textController', function($scope,$routeParams){
    $scope.$watch('taskarrbroad.length', function(){
        console.log($scope.taskarr.map(function(task){
            return task.content;
        }).join('\n'));

    })
})

Here I can access $scope.taskarr and update it, but the view isn't updated. $scope.$apply() didn't help either (the timeout is because it's already within a digest.

controller('stateSwitchController', function($scope, $routeParams, $timeout){
    $scope.taskarr = $scope.$store[$routeParams.state].taskarr || [];
        console.log($scope.taskarr);
    $timeout(function() {
        $scope.$apply();
    })
}).

Upvotes: 0

Views: 58

Answers (1)

Anders Ekdahl
Anders Ekdahl

Reputation: 22933

$broadcast is a way to send events to other parts of your application. When you broadcast an event, someone else has to listen to that even with $on(). Something like:

// Some controller
$rootScope.$broadcast('my-event', eventData);

// Some other controller
$scope.$on('my-event', function() {
  console.log('my-event fired!')
});

$watch is something else, it's not an event listener per se, it's a way to attach a function that gets called when that value changes, and that value has to be on the scope. So your watch should look like this:

$scope.$watch('taskarr.length', function(){

});

Since you've named the array taskarr on the scope.

Upvotes: 1

Related Questions