【问题标题】:AngularJS directive with isolated scope doesn't set local scope具有隔离范围的 AngularJS 指令未设置本地范围
【发布时间】: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


【解决方案1】:

您的问题是ng-if。来自https://docs.angularjs.org/api/ng/directive/ngIf的 API 页面

请注意,当使用 ngIf 删除元素时,它的作用域将被破坏,而当元素恢复时会创建一个新作用域。

所以每次ng-if 评估为true 时,都会创建一个不引用您的errorText 的新范围。另一方面,如果您使用ng-show,它会隐藏/显示但保持范围,并且一切正常。

<div class="row" ng-show="isAmountError">

这是更新的 plunkr http://plnkr.co/edit/BsSueLNpWA8XveyxblmE?p=preview

【讨论】:

  • 有趣的是,如果您引用{{$parent.errorText}},它可以与ng-if 一起使用。这支持了创建新子作用域的想法。
  • 查看我拥有的错误模板的数量。我选择了 ng-if 而不是 ng-show。我不希望每次验证都加载 DOM。
  • 好的。但这绝对是问题的根源。
猜你喜欢
  • 2019-10-21
  • 1970-01-01
  • 1970-01-01
  • 2013-03-15
  • 1970-01-01
  • 1970-01-01
  • 2015-03-17
  • 1970-01-01
相关资源
最近更新 更多