这令我惊讶。如果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;
}
});
}
};
});
答案 0 :(得分:2)
您的问题是ng-if
。来自https://docs.angularjs.org/api/ng/directive/ngIf
Note that when an element is removed using ngIf its scope is destroyed and a new scope is created when the element is restored.
因此,每次ng-if
评估true
时,都会创建一个新范围,但不会引用您的errorText
。另一方面,如果您使用ng-show
,它会隐藏/显示但保留范围,并且一切正常。
<div class="row" ng-show="isAmountError">
这是更新的plunkr http://plnkr.co/edit/BsSueLNpWA8XveyxblmE?p=preview