Dinesh Kumar Dinesh Kumar - 2 months ago 58
AngularJS Question

How to use $watch in angularjs component

I am using jCarousel for image thumbnail slider. but previously I was using directive for the same but now I changed my code to component. but now I am not able to use that link function and watch reload in component. because I am using first time component in agularjs.

//Previous code

directive('jblogcarousel', function() {
return {
restrict: 'A',
replace: true,
transclude: true,
scope: {
jitems: "="
},
templateUrl: '/templates/blog-carousel.html',

link: function link(scope, element, attrs) {
var container = $(element);
var carousel = container.find('.jcarousel');

carousel.jcarousel({
wrap: 'circular'
});

scope.$watch(attrs.jitems, function (value) {
carousel.jcarousel('reload');
});

container.find('.jcarousel-control-prev')
.jcarouselControl({
target: '-=1'
});

container.find('.jcarousel-control-next')
.jcarouselControl({
target: '+=1'
});
}
};


});

//Current code

.component('jCarousel', {
bindings: {
jitems: '='
},
templateUrl: '/templates/carousel.html'


})

Answer

From what I understood, in Angular 1.5 components bindings will bind the value to the controller.

So you can add a controller (with a $watch inside):

// bindings: { ... },
// templateUrl: '...',
controller: function ($scope) {
    var vm = this;
    console.log(vm.jitems); // vm.jitems should exist and be bound the value you passed to the component from the outside

    // you should be able to watch this value like this
    $scope.$watch(
        function () { return vm.jitems; },
        function (newValue) { console.log(newValue); }
    );
}

Also, with components, you should in most situations use one way binding '<' instead of two-way binding '=', and use functions/events (binding '&') for the other direction.