Search code examples
javascriptjqueryangularjsjquery-knob

Why doesn't the background color of the knob load before click? [Angular.js]


I will keep this simple. You can check this fiddle here jsfiddle. Here when you load the knob, the color of the knob only gets updated on clicking/scrolling over it (the number changes and hence colors up). I have this same problem on my project and was hesitant to ask this as I was skeptic if I could properly make you understand my question. Now that I have this fiddle, I hope you all can see what is happening. I am new to angular.js. Every answer is a learning experience for me. Thanks in advance.

view

<div ng-app="Knob" ng-controller="myCtrl">
<input type="text" ng-model="number" knob class="dial">
</div>  

Controller + Directive

var App = angular.module('Knob', []);
App.controller('myCtrl', function($scope) {
    $scope.number = 24;
})

App.directive('knob', function() {
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            $(element).knob();
        }
    };
});

Solution

  • I believe it the directive is being called before it has the value. Wrapping it in a timeout works.

    App.directive('knob',['$timeout', function ($timeout) {
        return {
            restrict: 'A',
            link: function(scope, element, attrs) {            
                $timeout(function () { // You might need this timeout to be sure its run after DOM render.
                    $(element).knob();
                }, 0, false);
            }
        };
    }]);