Tropicalista
Tropicalista

Reputation: 3137

AngularJs passing a value to a directive

I'm trying to pass a value to a directive. The directive is used to integrate a jquery plugin Knob

JSFIDDLE: http://jsfiddle.net/Tropicalista/TH87t/93/

I have this code:

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().val(scope.number); 
        console.log(attrs)
    }
};
});

Upvotes: 1

Views: 2023

Answers (2)

damthatmad
damthatmad

Reputation: 21

I used your question as reference for a fully bi-direction binding. For a working version with angular 1.2.1 see http://jsfiddle.net/sander_van_dam/m5YJu/

App.directive('knob', function() {
    return {
        require: 'ngModel',
        scope: { model: '=ngModel' },
        controller: function($scope, $element, $timeout) {
                var el = $($element);
                $scope.$watch('model', function(v) {
                    var el = $($element);
                    el.val(v).trigger('change');
                });
        },

        link: function($scope, $element, $attrs,$ngModel) {
                    var el = $($element);
                    el.val($scope.value).knob(
                        {
                            'change' : function (v) {
                                $scope.$apply(function () {
                                  $ngModel.$setViewValue(v);
                            });
                        }
                        }
                    );
        }
    }

});

Upvotes: 2

Joseph Silber
Joseph Silber

Reputation: 220136

The problem is that knob() doesn't return the element. Use this instead:

link: function(scope, element, attrs) {
    $(element).val(scope.number).knob();
}

Here's your fiddle: http://jsfiddle.net/TH87t/94/

Upvotes: 2

Related Questions