AngularJS 自定义属性不评估第一次指令运行
AngularJS custom attribute does not evaluate first time directive runs
HTML
<a custom-attr='{{ controller.object.value }}' data-ng-model='controller.object.value'>
Angular 指令
.directive('customAttr', function () {
return {
require: 'ngModel',
controller: 'ControllerName',
controllerAs: 'cName',
link: function (scope, el, attr, ctrl) {
el.on('click', function ($event) {
if (ctrl.$viewValue && attr.customAttr) { // breakpoint
}
})
}
}
})
目标:
在指令第一次运行时 attr.customAttr
中看到正确的值。
描述
在指令的 link 函数内的 if 语句的断点处停止,我希望看到一个布尔值。我已经使用 $log.log()
验证了模型中的布尔值是正确的。不幸的是,指令第一次运行时,attr.customAttr
计算为模型值引用的字符串(调试器中的 'controller.object.value'
),然后在指令的后续迭代中它正确计算为布尔值.我尝试从属性中删除花括号,但我只得到一个不变的空字符串。
我该怎么做才能使模型值在第一时间正确评估?
注意:我之前用数值做过类似的版本没有问题。关键区别似乎是工作版本在输入元素上,并且具有 ngModel 和 ngValue 属性。
考虑使用
attrs.$observe('customAttr', function() {
scope.customAttr= scope.$eval(attrs.customAttr);
});
正确地将 .attrs(并因此可能解决您的问题)双重绑定到您的指令。
更多信息在此answer and in the docs。
事实证明,controller 和 controllerAs 属性对此有影响。我删除了它,但后来决定我宁愿拥有控制器,所以我使用隔离范围来评估对象而不是从 attr 属性.
读取它
HTML
<a custom-attr='{{ controller.object.value }}' data-ng-model='controller.object.value'>
Angular 指令
.directive('customAttr', function () {
return {
require: 'ngModel',
controller: 'ControllerName',
controllerAs: 'cName',
link: function (scope, el, attr, ctrl) {
el.on('click', function ($event) {
if (ctrl.$viewValue && attr.customAttr) { // breakpoint
}
})
}
}
})
目标:
在指令第一次运行时 attr.customAttr
中看到正确的值。
描述
在指令的 link 函数内的 if 语句的断点处停止,我希望看到一个布尔值。我已经使用 $log.log()
验证了模型中的布尔值是正确的。不幸的是,指令第一次运行时,attr.customAttr
计算为模型值引用的字符串(调试器中的 'controller.object.value'
),然后在指令的后续迭代中它正确计算为布尔值.我尝试从属性中删除花括号,但我只得到一个不变的空字符串。
我该怎么做才能使模型值在第一时间正确评估?
注意:我之前用数值做过类似的版本没有问题。关键区别似乎是工作版本在输入元素上,并且具有 ngModel 和 ngValue 属性。
考虑使用
attrs.$observe('customAttr', function() {
scope.customAttr= scope.$eval(attrs.customAttr);
});
正确地将 .attrs(并因此可能解决您的问题)双重绑定到您的指令。
更多信息在此answer and in the docs。
事实证明,controller 和 controllerAs 属性对此有影响。我删除了它,但后来决定我宁愿拥有控制器,所以我使用隔离范围来评估对象而不是从 attr 属性.
读取它