d_z90 d_z90 - 2 months ago 21
HTML Question

Pass scope value from Directive to Controller - AngularJS

I have a small script with a countdown, created through a

directive
, which starts if a
$scope
value inside the
controller
is
true
. This is the
html
code:

<countdown from="3" start-if="{{startCountdown}}"></countdown>


Followed by the code of the
directive
:

app.directive('countdown', function ($interval) {
return {
restrict: 'E',
template: '{{count}}',
controller: function($scope, $element, $attrs) {
$scope.count = $attrs.from;

function countdown(){
var intervalID = $interval(function() {
if ($scope.count > 0) {
$scope.count--;
} else {
$interval.cancel(intervalID);
}
}, 1000);
}

$attrs.$observe('startIf', function(value) {
if (value) {
countdown();
}
});
}
}
});


The countdown is working properly but inside the
controller
, if
$scope.count === 0
, there should be an
alert()
but it is not working.

This is a Plnkr with the complete code. Do you know how to pass the value of
$scope.count
to the
controller
and solve this issue? Thanks in advance for your replies!

Answer

You can use $broadcast to achieve this with same code.

controller: function($scope, $element, $attrs) {
  $scope.count = $attrs.from;

  function countdown(){
    var intervalID = $interval(function() {
      $scope.$broadcast('counterVal',{
          countVal:$scope.count
        });
      if ($scope.count > 0) {
        $scope.count--;

      } else {
        $interval.cancel(intervalID);
      }
    }, 1000);
  }

  $attrs.$observe('startIf', function(value) {
    if (value) {
      countdown();
    }
  });
}

Please find the working plunker here.