渲染 Angular 指令后调用 js 函数
Call js function after rendering Angular directive
我正在尝试创建一个快速 Angular 指令,它将使用我找到的 jQuery UI 扩展名生成组合框。
扩展很简单。我只需要创建一个标准的 select 元素,然后在其上 运行 函数 "combobox()"。不过,我不确定在我的 angular 指令中在哪里执行此操作。
partials/elements/combobox.html
<select class="dropdown" ng-options="option as option for option in selectOptions" ng-model="selectModel" />
应用-directives.js
appDirectives.directive('combobox', function() {
return {
restrict: 'E',
templateUrl: 'partials/elements/combobox.html',
scope: {
selectModel: "=model",
selectOptions: "=options"
}
};
});
在我看来
<combobox model="query.favouriteFruit" options="fruits"></combobox>
我不确定我应该将对 .combobox() 的调用放在哪里。我试过这样做:
$(function() { $("combobox select").combobox(); });
但这当然行不通,因为指令没有及时呈现。有没有办法只在指令完成渲染时调用它?
感谢您的宝贵时间,
安迪
您可以在指令的 link 函数中处理该逻辑。
appDirectives.directive('combobox', function($timeout) {
return {
restrict: 'E',
templateUrl: 'partials/elements/combobox.html',
scope: {
selectModel: "=model",
selectOptions: "=options"
},
link: function (scope, element, attrs) {
// wait till the initial digest cycle is triggered.
$timeout(function () {
// change the select to combobox
element.combobox();
});
}
};
});
我正在尝试创建一个快速 Angular 指令,它将使用我找到的 jQuery UI 扩展名生成组合框。
扩展很简单。我只需要创建一个标准的 select 元素,然后在其上 运行 函数 "combobox()"。不过,我不确定在我的 angular 指令中在哪里执行此操作。
partials/elements/combobox.html
<select class="dropdown" ng-options="option as option for option in selectOptions" ng-model="selectModel" />
应用-directives.js
appDirectives.directive('combobox', function() {
return {
restrict: 'E',
templateUrl: 'partials/elements/combobox.html',
scope: {
selectModel: "=model",
selectOptions: "=options"
}
};
});
在我看来
<combobox model="query.favouriteFruit" options="fruits"></combobox>
我不确定我应该将对 .combobox() 的调用放在哪里。我试过这样做:
$(function() { $("combobox select").combobox(); });
但这当然行不通,因为指令没有及时呈现。有没有办法只在指令完成渲染时调用它?
感谢您的宝贵时间, 安迪
您可以在指令的 link 函数中处理该逻辑。
appDirectives.directive('combobox', function($timeout) {
return {
restrict: 'E',
templateUrl: 'partials/elements/combobox.html',
scope: {
selectModel: "=model",
selectOptions: "=options"
},
link: function (scope, element, attrs) {
// wait till the initial digest cycle is triggered.
$timeout(function () {
// change the select to combobox
element.combobox();
});
}
};
});