AngularJS - 与Jquery inside指令结合使用的指令

时间:2014-08-01 13:41:25

标签: jquery angularjs jquery-plugins angularjs-directive

如何实现我的激活&#39; jQuery(element).scombobox()指向未准备好的<select>

要查看更多详情,请参阅 http://plnkr.co/edit

这是html:

<div tu-combobox="" ng-model="comboboxvalue" options="combobox.options"></div>

我有这个指令:

.directive('tuCombobox', function($compile) {
        return {
            restrict: 'A',
            replace: true,
            require: 'ngModel',
            scope: {
                feature: '=',
                options: '=',
                tudisabled: '='
            },
            template: '<select ng-disabled="tudisabled" ng-options="option.value as option.text for option in options"></select>',
            link: function(scope, element, attributes, ngModel) {


  // this doesn't work because the template isn't yet rendered
            //element.scombobox();


  // but using this i get a bunch of errors $rootScope:inprogress

          scope.$watch('ngModel', function(){
            element.scombobox();
           });


          }
        };
    })

为什么这么难实现?

2 个答案:

答案 0 :(得分:0)

由于模板是异步检索的(即使在本地可用,例如$templateCache),你需要在Angular完成其“东西”之后执行你的代码。
最安全的是在所有待处理操作完成后使用$timeout执行代码。


E.g:

.directive('tuCombobox', function ($timeout) {
    return {
        ...
        link: function tuComboboxPostLink(scope, elem) {
            $timeout(function () {
                elem.scombobox();
            });
        }
    };
});

<强> Updated plunkr

答案 1 :(得分:0)

Bellow我试图将jquery datetimepicker指令改编为你的组合框,我没有编译它,所以你需要对它进行修改。

.directive('tuCombobox', function($compile) {
        return {
            restrict: 'EA',
            replace: true,
            require: 'ngModel',
            scope: {
                feature: '=',
                options: '=',
                tudisabled: '='
            },
            compile: function(element, attrs) {
                var modelAccessor = $parse(attrs.ngModel);

                var html = '<select ng-disabled="tudisabled" ng-options="option.value       as option.text for option in options"></select>';

                var newElem = $(html);
                element.replaceWith(newElem)

        return function(scope, element, attributes, ngModel) {

           var processSelection = function () {
                var selection = element.combox("getvalue");
                scope.$apply(function (scope) {
                    // Change bound variable
                    modelAccessor.assign(scope, selection;
                });
            };
            //if option is selected on UI
            element.combobox({onSelect:processSelection});

            //If option is set from code
            scope.$watch(modelAccessor, function(val){
                element.combobox("setValue",val);
              })
          }
            }
        };
    });