【问题标题】:$scope.myVariable not updated in controller for angular-ui bootstrap modal$scope.myVariable 未在 angular-ui 引导模式的控制器中更新
【发布时间】:2013-10-16 11:14:26
【问题描述】:

在我看来,我有一个输入、一个跨度和一个按钮,如下所示:

<script type="text/ng-template" id="myTemplate.html">
  <input type="text" ng-model="phoneNumber">
  <span>{{ phoneNumber}}</span>
  <input type="button" ng-click="click()">
</script>

在文本框中输入时,span 的内容会按预期更新。但是当点击按钮时,phoneNumber 并没有在控制器内部更新:

app.controller('myPopopCtrl', ['$scope', '$modalInstance',
  function ($scope, $modalInstance) {
      $scope.phoneNumber= '';    

      $scope.click = function() {
        alert($scope.phoneNumber); // alerts only ''
      };

您是否会在 Angular 中犯一些新错误,导致控制器内的 $scope 上的内容无法更新?

我需要注意angular-ui modal 的 $scope 问题吗?

编辑:

似乎phoneNumber 是在 2 个作用域中创建的。一次在phoneNumber: '' 的蓝色箭头的范围内,一次在红色箭头的子范围内。视图在子作用域中使用phoneNumber,控制器在父作用域中使用phoneNumber...

为什么要创建两个作用域?

【问题讨论】:

  • 点击方法在哪里定义?
  • click 方法是在 popupController 中定义的,(我更新了问题以澄清)
  • 那么更好的选择是传递一个对象而不是字符串,因为字符串分配会在子范围内创建一个新字符串。创建类似$scope.phone={number:null} 的内容并传递它。

标签: angularjs angular-ui angular-ui-bootstrap


【解决方案1】:

ng-include 创建一个新范围。所以传递一个对象而不是字符串

$scope.phone={number:null}

模板看起来像

<script type="text/ng-template" id="myTemplate.html">
  <input type="text" ng-model="phone.number">
  <span>{{ phone.number}}</span>
  <input type="button" ng-click="click()">
</script>

查看wiki 以了解原型继承的问题。

【讨论】:

  • 永远不会猜到这些问题存在于角度......谢谢:)
  • 这是数小时的心碎,试图弄清楚为什么我的模态不工作,直到我偶然发现这一点,谢谢。
【解决方案2】:

遇到了同样的问题,经过几次实验,我决定写了

<input type="text" ng-model="$parent.phoneNumber">

这种方式输入绑定到蓝色范围,这正是你想要的。

另一种方法是使用真实值初始化 phoneNumber。试试$scope.phoneNumber= '123'; - 对我来说效果很好。

Angular 似乎沿着作用域树向上寻找要绑定的属性。如果没有找到 - 它会绑定到最里面的范围,即图片中的红色范围。 正如其他答案所暗示的那样 - 这个红色范围是由 ng-include 创建的,作为控制器 $scope 的子级。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-11-10
    • 2013-03-02
    • 2016-01-08
    • 1970-01-01
    • 1970-01-01
    • 2016-02-29
    • 1970-01-01
    • 2021-10-20
    相关资源
    最近更新 更多