在下面的代码中,我正在编译一个包含ng-required表达式的指令。只要表达式为真或假,一切都很好,但是当ng-required =“appConfig.requireBirthdate”时,eval失败。所以,我一定是做错了。在编译指令的上下文中,如何获得ng-required表达式的真假值?
代码的最后一行是我遇到麻烦的地方,问题在于eval()eval不会发生在定义该表达式的范围的上下文中。
return {
restrict: 'E',
priority: 102, // We need this directive to happen before ng-model and the boolean directives
terminal: true, // We are going to deal with this element
compile: function(element, attrs) {
if ( attrs.ngRepeat || attrs.ngSwitch || attrs.uiIf ) {
throw new Error('The ng-repeat, ng-switch and ui-if directives are not supported on the same element as the field directive.');
}
if ( !attrs.ngModel ) {
throw new Error('The ng-model directive must appear on the field element');
}
// Extract the label and validation message info from the directive's original element
var validationMessages = getValidationMessageMap(element);
var labelContent = getLabelContent(element, eval(attrs['ngRequired']));
答案 0 :(得分:0)
使用$ eval:
对范围计算角度表达式$scope.$eval('a+b');
您可以在此处查看文档:{{3}}
但是,在您的示例中,我只看到编译函数,并且在编译时,指令的作用域不可用。范围链接到指令,您可以在指令定义中使用link
回调:
{
priority: 102,
terminal: true,
link: function( $scope, $el, $attrs ) {
alert($scope.$eval('appConfig.requireBirthdate') )
}
}
或者,您可以使用隔离范围绑定来使用动态属性:
{
priority: 102,
terminal: true
scope: {
required: '&ngRequired'
},
link: function( scope, $el, $attrs ) {
alert( $attrs.required() );
}
}
指令绑定的文档可以在官方指令指南中找到:https://docs.angularjs.org/api/ng/type/$rootScope.Scope。
但你可能会以一种愚蠢的方式获得父范围:
compile: function( element, attrs ) {
scope = angular.element(element).scope();
}