【问题标题】:$scope variable not updating in view$scope 变量不在视图中更新
【发布时间】:2016-08-06 17:08:27
【问题描述】:

我有以下sn-p的代码,

<div ng-controller="GraphCtrl" ng-if="errorTracerouteResultsLength!=0">
  <h5>Erroneous Traceroute Paths
    <small>Sub-heading</small>
  </h5>

  <a href="#"  ng-repeat="(key, val) in errorTracerouteResults" ng-click="loadTraceroutePath(val.metadata);">
    S: {{val.source.ip}}
    D: {{val.destination.ip}}
  </a>
</div>

它工作正常,loadTraceroutePath 属于另一个控制器,(让我们称之为 X)但不知何故 ng-click 工作和 console.log 打印出正确的元数据值。

但是,在控制器 X 中,我有,

$scope.loadIndividualTraceroutePath = function (metadataKey) {
   $scope.noOfResults = 1;
}

在 html 中,我到处都有{{noOfResults}}。其中一些能够显示 1 而有些则不能。我已经附加了ng-controller 指令并指向控制器X,但是{{noOfResults}} 没有显示。

如何让{{noOfResults}} 显示在 HTML 的任何部分?

编辑:我已经添加了 HTML。

<div class="row">
  <div class="col-lg-9">
    <div class="panel panel-default">
      <div class="panel-heading">
        <i class="fa fa-bar-chart-o fa-fw"></i> Visualisation
        <div class="pull-right">
          Layout
        </div>
      </div>
      <!-- /.panel-heading -->
      <div class="panel-body">

        <div class="container" ng-controller="X">
          <!--This does not work-->
          {{noOfResults}}
        </div>

        <div>

          <div ng-controller="IndividualTraceroutePathGraphCtrl" id="individual_traceroute_path_graph"></div>

        </div>

      </div>
      <!-- /.panel-body -->
    </div>
    <!-- /.panel -->
  </div>

这个问题第一部分的 ng 点击在下面。

【问题讨论】:

  • 只是想使用 $rootScope 更新,HTML 中的所有 {{noOfResults}} 都会更新。但我仍然想知道出于学习目的有什么问题。
  • 在定义原始类型变量并希望在ng-if/ng-repeat中显示时使用Dot rule,更多信息请参考this answer

标签: javascript angularjs


【解决方案1】:

最后你有一个额外的;,你也没有使用你作为参数传递给函数的对象,因此改变

发件人:

<a href="#"  ng-repeat="(key, val) in errorTracerouteResults" ng-click="loadTraceroutePath(val.metadata);">

收件人:

<a href="#"  ng-repeat="(key, val) in errorTracerouteResults" ng-click="loadTraceroutePath(val)">

那么,

$scope.loadIndividualTraceroutePath = function (metadataKey) {
   $scope.noOfResults = 1;
}

编辑

你不需要在视图中提到这么多控制器,有一个控制器在其中定义了功能并删除其余的,这里,像这样更新,

   <div class="container" >
          <!--This does not work-->
          {{noOfResults}}
        </div>
        <div>
          <div id="individual_traceroute_path_graph"></div>
        </div>
    </div>

【讨论】:

  • 我已经尝试了 ng-click 的所有组合(带/不带分号)和 val.metadata/val。值本身可以很好地传递给函数。问题在于 $scope 在某些地方没有更新。
  • @ParkTaecyeon 您在视图中显示 noOfResults 的地方在哪里
  • 如果我有几个用于一个 HTML 的控制器,我应该如何声明它们?我一直想为访问数据的每个标签声明控制器。我是否将所有内容都放在身体中,然后是带有第二个控制器的身体中的 div,然后是第三个控制器,等等。
  • @Sajeetharan。确保额外的分号绝对不会影响任何东西
  • @developer033 我同意 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-05-11
  • 2015-12-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-16
  • 1970-01-01
相关资源
最近更新 更多