M
M
MakPET2016-04-03 17:27:26
JavaScript
MakPET, 2016-04-03 17:27:26

Why doesn't $digest() work in angularjs?

HTML

<div ng-controller="MainCtrl">

<div class="btn-group" tri-button counter="buttons.totalClick" >
  <button class="btn btn-default" ng-repeat="name in buttons.names">{{name}}</button>
</div>
<h5>{{buttons.totalClick}}</h5>
</div>

//  app.js

var TestApp = angular.module('TestApp', []);

// controller.js

angular.module('TestApp')
.controller('MainCtrl', ['$scope', function ($scope) {
  $scope.buttons = {
    names:['Button #1','Button #2','Button #3'],
    totalClick:0
  }
}]);

//directive.js

angular.module('TestApp')
.directive('triButton', [function () {
  return {
    scope:{counter:'=counter'},
    link: function (scope, elem, attr) {
      elem.on('click',function(event){
          scope.counter++
          scope.$digest();
          console.log(scope.counter)
      })

    }
  };
}])

in the console it increases but in the DOM no
I know this code works but I need it with digest()
elem.on('click',function(event){
          scope.$apply(scope.counter++)
          console.log(scope.counter)
      })

Answer the question

In order to leave comments, you need to log in

1 answer(s)
_
_ _, 2016-04-03
@MakPET

Because $digest is a change check ONLY for the scope it is called on. And $apply runs a check on the entire tree.
Your directive creates a private scope, so $digest does not apply to the scope of the controller.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question