【发布时间】:2014-12-04 16:01:59
【问题描述】:
这让我大吃一惊。如果 AngularJS 指令与隔离范围一起使用,则不会设置本地范围。
我有一个正在验证的金额字段。验证消息位于监视数量的指令中,如果大于 5,则应显示错误消息。然而,错误信息并没有显示出来,而是模板响应了在本地范围内声明了属性的 ng-if。
下面是代码和PLUNKR
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.vm = {};
});
app.directive('errorMessage', function() {
return {
restrict: "E",
replace: true,
templateUrl: 'my-template.tpl.html',
scope: {
amount: '='
},
link: function(scope, element, attrs) {
scope.isAmountError = true;
scope.$watch('amount', function() {
if (scope.amount > 5) {
scope.isAmountError = true;
scope.errorText = 'Amount lesser than 5';
} else {
scope.isAmountError = false;
}
});
}
};
});
【问题讨论】:
-
为什么要设置
replace: true?如果删除此行,一切正常。 -
@DavinTryon 那更奇怪了。为什么重要?
-
感觉就像是使用了隔离作用域,它不会让你……哦,等一下,我想就是这样。不,不是。
-
什么替换:真?那有什么关系呢?是的,它虽然有效。但是有什么区别呢?
标签: angularjs angularjs-directive