【问题标题】:Angularjs 1.4 - Two ways binding - Input text changed but scope does not?Angularjs 1.4 - 两种绑定方式 - 输入文本更改但范围没有?
【发布时间】:2018-11-03 17:08:03
【问题描述】:

我对 AngularJS 1.4 (TypeScript) 有一个非常奇怪的问题。问题出在控制器中,我有一个变量,可以在输入文本框中查看该值。 但是,当我编辑此文本框中的值并单击按钮时,此变量的值不会改变(!)。

HTML 视图

<div class="form-group">   
     <label>Title</label>
     <input class="form-control" ng-model="serviceTitle">
</div>


<div class="form-group">
     <button class="btn btn-primary" ng-click="updateServiceIdentification()">Update Service Identifcation</button>
</div>

控制器:

 $scope.serviceTitle = "Test";

 $scope.updateServiceIdentification = ()=> {
    // after changing value in view, the value here is still "Test"????
    alert($scope.serviceTitle);
 }

如果我在 HTML 视图中添加测试标签

<h1>{{serviceTitle}}</h1>

当我更改输入文本框的值时,新的值可以打印在这个标签中。

【问题讨论】:

  • 尝试不使用$scope
  • @KaustubhKhare 你是什么意思????
  • 喜欢这个alert(serviceTitle);alert(this.serviceTitle);
  • [ts] 对于这两种情况,“AdminOWSMetadataManagementController”类型都不存在属性“serviceTitle”。
  • 可能想在stackoverflow.com/questions/12618342/…查看答案。

标签: angularjs typescript angularjs-directive angularjs-scope


【解决方案1】:

问题来自这个并导致我几个小时。如果我在此元素下添加文本框,它将无法工作。把它放在外面,alert() 从文本框中返回改变后的值。

    <input class="form-control" ng-model="serviceTitle">
    <input type="button" class="btn btn-primary" ng-click="updateServiceIdentification()" value="Update Service Identifcation"/>
    <accordion>
            <accordion-group>
              <accordion-heading>
                        some text here, on the left side of the header.

                        <div class="pull-right">
                          <span>1st info</span>
                          <span>2nd info</span>
                          <span>maybe 3rd?</span>
                        </div>                
              </accordion-heading>
             <!------------ Doesn't work if it is inside ------------->
            </accordion-group>    
          </accordion>

真正的问题应该是“这是因为字符串是原始的。当 Angular 分配值时,它会更改指向该值的指针,因此控制器会查看旧值,因为它具有指向该值的旧指针。”大马士 - Ng-model does not update controller value

像这样更新控制器:

$scope.output = {serviceTitle: "1234567"};                
$scope.serviceTitle = "asdadasdsad";

$scope.updateServiceIdentification = (...args: any[])=> {
     alert($scope.output.serviceTitle);
}

并且它可以在手风琴元素下工作。

   <uib-accordion close-others="false">
       <uib-accordion-group is-open="isAvailableLayersOpen">
           <input class="form-control" ng-model="output.serviceTitle">
           <input type="button" class="btn btn-primary" ng-click="updateServiceIdentification()" value="Update Service Identifcation"/>
       </uib-accordion-group>
  </uib-accordion>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-02-13
    • 2014-05-26
    • 2014-10-07
    • 1970-01-01
    • 2016-02-27
    • 2013-03-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多