Search code examples
angularjsangularjs-scopeangular-carousel

Changing Angular Carousel Position with Directive->controller change not working


I am trying to create some event triggers to change the position of an Angular Carousel (Github repo).

See the plunker for a working version

The expected behavior is that you click the text that says "Go to position: 0" and the Carousel will change index position to 0.

This is accomplished using two-way binding on the Carousel: rn-carousel-index="carouselIndex"

This scope value is passed to a directive by setting: carousel-index="carouselIndex"

A controller method to modify carouselIndex is also passed to the directive with: index-model="indexModel(value)"

The directive takes the scopes and has a function bound to the text that should change the Carousel position:

app.directive('timeline', function () {
  return {
    replace:true,
    scope:{
     indexModel:'&',
     carouselIndex:'='
    },

    link:function (scope, element, attrs) {


          var valueto = 0;

        var textElement = d3.select(".timeLine").text('Go to position: ' + valueto)
        textElement
          .on('click',clickMe)

        function clickMe(d){
          console.log('click');
          console.log("but index is: " + scope.carouselIndex);

          scope.carouselIndex = valueto;
         // scope.$apply(carouselIndex) = valueto;
          scope.indexModel({value: valueto});
          //alert(d);
        }

    }
  }
})

As you can see, when you click, the watcher on $carouselIndex does not always change. Moreover, and more importantly, the Carousel behavior to change position is not working.

$scope.$watch('carouselIndex', function(a,b) {
      console.log('change detected');
      console.log('Index really is: ' + $scope.carouselIndex);
    })

Solution

  • Adding a digest() $apply() function solved the problem.

        $scope.indexModel = function(slide) {
          $scope.$apply(function() {
            console.log('change slide ' + slide);
    
            var changeSlide = parseInt(slide);
            $scope.carouselIndex = changeSlide;
            console.log('Index should be: ' + $scope.carouselIndex);
         )}
       };