Rober
Rober

Reputation: 6118

Inject $element in angularjs Controller

first, I have read millions of post saying you should not update DOM elements from a Controller in Angular. I know.

When trying to use angular-timer directive (a countdown). I faced some problems, so finally, with the plugin developer help, we did this plunker, which is working and meet my requirements.

http://plnkr.co/edit/CWXnKMbygVDMc8xzshZa?p=preview

However, when moving this code to my app, I got next error when I add the $element to my controller:

 `Error: Unknown provider: $elementProvider <- $element`

I have read many posts and I know it can be injected, but I don´t know why it´s not working in my app.

In the other hand, I like to do things right, so I don´t like to implement something that is a bad practice. So, if you have a better approach that works, please let me know.

Upvotes: 1

Views: 1864

Answers (1)

charlietfl
charlietfl

Reputation: 171698

Looks ugly parsing DOM with jQuery, and I don't understand why you don't use the timer directive within the ng-repeat.

Here's an approach that just adds and extra array to scope for eleapsedTimers which are then displayed using ng-repeat

 $scope.elapsedTimers=[];

$scope.$on('timer-stopped', function (data) {
    /* loop through bookings to find one that just stopped*/
    var now = new Date();
    angular.forEach($scope.bookingsList, function (item) {
        if (!item.elapsed) {
            if (item.booking_date <= now) {                  
                item.elapsed = true;
                $scope.$apply(function () {
                    $scope.elapsedTimers.push(item)
                });
            }
        }
    });
});

HTML

<div id="result">
  <div ng-repeat="item in elapsedTimers">ID {{item.id}} elapsed</div>
</div>

DEMO

Note...this will add a new property elapsed to the booking object. If this is a problem can create workaround

Upvotes: 1

Related Questions