AngularJs将值传递给指令

时间:2013-09-16 02:30:41

标签: angularjs

我试图将值传递给指令。该指令用于集成jquery插件Knob

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

我有这段代码:

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)
    }
};
});

2 个答案:

答案 0 :(得分:2)

问题是knob()没有返回元素。请改用:

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

这是你的小提琴:http://jsfiddle.net/TH87t/94/

答案 1 :(得分:2)

我使用您的问题作为完全双向绑定的参考。对于角度为1.2.1的工作版本,请参阅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);
                            });
                        }
                        }
                    );
        }
    }

});