如何创建一个指令,对于NG选项提供值? [英] How to create a directive that provides values for ng-options?
本文介绍了如何创建一个指令,对于NG选项提供值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有有在整个应用程序相同的选项中选择元素,但看起来可能有点不同,例如选择用户的生日(日,月,年)。
I've got select elements that have the same options across the whole app, but may look a bit differently, e.g. selects for user's birthday (day, month, year).
有没有一种方法来创建一个指令,将提供价值/ EX pression为 NG-选项
?
Is there a way to create a directive that would provide values/expression for ng-options
?
例如。 <选择我的选项月>< /选择>
,其中我的选项个月
会自动创建同值的选项 1..12
使用 NG-选项
指令。
E.g. <select my-options-months></select>
, where my-options-months
would automatically create options with values 1..12
using ng-options
directive.
推荐答案
更新答案
你的指令将是这样的:
Updated answer Your directive would like this:
var myapp = angular.module('myapp', []);
myapp.controller('FirstCtrl', function ($scope) {
$scope.selectedMonth = 3
})
.directive('myOptionsMonths', function ($compile) {
return {
priority: 1001, // compiles first
terminal: true, // prevent lower priority directives to compile after it
compile: function (element, attrs) {
element.attr("ng-options", "m for m in months");
element.removeAttr('my-options-months'); // necessary to avoid infinite compile loop
var fn = $compile(element);
return function (scope) {
scope.months = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
fn(scope);
};
}
}
})
请,结账拨弄例如 http://jsfiddle.net/KN9xx/39/
这篇关于如何创建一个指令,对于NG选项提供值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文