Ken*_*eld 143 javascript options default-value angularjs angularjs-directive
我刚开始使用angularjs,我正在努力将一些旧的JQuery插件转换为Angular指令.我想为my(element)指令定义一组默认选项,可以通过在属性中指定选项值来覆盖它.
我已经浏览了其他人的方式,在angular-ui库中,ui.bootstrap.pagination似乎做了类似的事情.
首先,所有默认选项都在常量对象中定义:
.constant('paginationConfig', {
itemsPerPage: 10,
boundaryLinks: false,
...
})
Run Code Online (Sandbox Code Playgroud)
然后将getAttributeValue实用程序函数附加到指令控制器:
this.getAttributeValue = function(attribute, defaultValue, interpolate) {
return (angular.isDefined(attribute) ?
(interpolate ? $interpolate(attribute)($scope.$parent) :
$scope.$parent.$eval(attribute)) : defaultValue);
};
Run Code Online (Sandbox Code Playgroud)
最后,这在链接函数中用于读入属性
.directive('pagination', ['$parse', 'paginationConfig', function($parse, config) {
...
controller: 'PaginationController',
link: function(scope, element, attrs, paginationCtrl) {
var boundaryLinks = paginationCtrl.getAttributeValue(attrs.boundaryLinks, config.boundaryLinks);
var firstText = paginationCtrl.getAttributeValue(attrs.firstText, config.firstText, true);
...
}
});
Run Code Online (Sandbox Code Playgroud)
对于想要替换一组默认值的标准内容,这似乎是一个相当复杂的设置.还有其他方法可以做到这一点吗?或者getAttributeValue以这种方式总是定义一个实用程序函数(如和解析选项)是否正常?我很想知道人们对这项共同任务采取了哪些不同的策略.
另外,作为奖励,我不清楚为什么interpolate需要这个参数.
小智 256
=?在指令的作用域块中使用该属性的标志.
angular.module('myApp',[])
.directive('myDirective', function(){
return {
template: 'hello {{name}}',
scope: {
// use the =? to denote the property as optional
name: '=?'
},
controller: function($scope){
// check if it was defined. If not - set a default
$scope.name = angular.isDefined($scope.name) ? $scope.name : 'default name';
}
}
});
Run Code Online (Sandbox Code Playgroud)
OZ_*_*OZ_ 108
您可以使用compile函数 - 读取属性(如果未设置) - 使用默认值填充它们.
.directive('pagination', ['$parse', 'paginationConfig', function($parse, config) {
...
controller: 'PaginationController',
compile: function(element, attrs){
if (!attrs.attrOne) { attrs.attrOne = 'default value'; }
if (!attrs.attrTwo) { attrs.attrTwo = 42; }
},
...
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
82389 次 |
| 最近记录: |