Dinesh Kumar Dinesh Kumar - 1 year ago 215
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');

wrap: 'circular'

scope.$watch(attrs.jitems, function (value) {

target: '-=1'

target: '+=1'


//Current code

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


Answer Source

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
        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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download