angular/ionic ng-click 不更新视图,但它在模型中更新

angular/ionic ng-click not updating the view, however it is updated in the model

我在使用 ng-click 更新 Ionic/Angular 中的视图时遇到了严重困难。

我之前遇到过类似的问题,但按照 this 指导解决了它,指导说明如果您的按钮在 < label > 内,则 ng-click 将不起作用。

我想达到什么目的?

我正在开发一个移动应用程序,并希望允许用户在必要时编辑他们的详细信息。为了以最简单的方式开始,我开始尝试实现用户可以编辑其姓名的功能。在下面的示例中,我试图在单击按钮时更改用户名。

奇怪的是,当我 console.log(Photos.name) 得到正确的值时,即 (scope.user.name = "Jim") 但是视图没有反映此更改。

我的代码如下:

控制器

.controller('ProfileCtrl', function($scope, Photos) {

    $scope.user = {
        "name": Photos.name
    }

    $scope.changeName = function() {
        Photos.changeName();
        console.log(Photos.name)
    };

})

工厂:

.factory('Photos', function(){
  var o = {
    name : 'James'
  }

  o.changeName = function(){
    o.name = 'Jim'
  }

  return o;

});

HTML 设置模板

这是在 profile.html 页面上更新用户名的按钮所在的位置(见下文)

 <ion-view view-title="Settings">
      <ion-content>
        <ion-list>
       <div class="item item-input">
        <span class="input-label">Change Profile Picture</span>
        <button type="button" ng-click="changeName()">Add</button>
      </div>
     </ion-list>
    </ion-content>
 </ion-view>

配置文件模板

<ion-view view-title="My Profile">
  <ion-content class="padding"> 

   <div class="item item-body">
     <p class="profile-details">
        {{user.name}}
     </p>
    </div>
  </ion-content>
</ion-view>

我已经阅读了许多 SO 答案和 ionic 网页上的答案,但没有运气。从我读过的内容来看,我认为这可能与在子范围内设置值有关是破坏它的事情,但我不能确定。

有人能帮忙吗?

我相信原因是一旦你这样做了:

$scope.user = {
    "name": Photos.name
}

你在那一刻$scope.user.name的值设置为Photos.name的值。

当您通过在工厂内执行 o.name = 'Jim' 来更改 Photos.name 时,您实际上是在分配 Photos.name 一个不同的字符串对象,而不是更改已经分配给 $scope.user.name.

您可以通过 $scope.user = Photos 而不是 $scope.user = { ... } 来证明我的理论(当然,只是作为概念的快速证明,而不是最终解决方案)。这样 $scope.user.name 将实际访问保存在 Photos 工厂中的 name 值。