AngularJS - 无法以编程方式更新模型

时间:2013-12-02 15:37:28

标签: javascript angularjs model

当我通过方法更新我的模型时,模型不会更新。下面是我的AngularJS代码:

var app = angular.module('MyApp',[]);

app.controller('businessCtrl', function($scope, Business) {
  $scope.businesses = Business.query();  // getting data using REST
  $scope.currentBusinessIndex = 0;
  $scope.changeBusinessIndex = function (indx) {
      if (indx) {
          $scope.currentBusinessIndex = indx;
      } else {
          $scope.currentBusinessIndex = 0;
      }
  };
});

以下是HTML:

<ul class="signups">
    <li ng-controller="businessCtrl" ng-repeat="business in businesses">
        <div class="user pull-left"  ng-click="changeBusinessIndex($index)">
            <img ng-src="http://localhost:8081{{business.logo.uri}}" alt="business logo" >
        </div>
        <div class="info" ng-click="changeBusinessIndex($index)">
            <h6 ng-cloak>{{business.name}}</h6>
            <small ng-cloak>{{business.streetAddress + ',' + business.city + ',' + business.country}}</small>
        </div>
    </li>
</ul>

<div id="business-image" class="main-container" ng-controller="businessCtrl">
    <img ng-src="http://localhost:8081{{businesses[currentBusinessIndex].logo.uri}}" alt="Business Logo">
</div>

问题:

在changeBusinessIndex()方法中,当我修改currentBusinessIndex时,它不会修改,因此“business-image”div中的图像不会更新。

2 个答案:

答案 0 :(得分:1)

您正在创建两个不同的businessCtrl实例,一个用于li(让我们称之为businessCtrl1),另一个用于business-image div(让我们称之为businessCtrl2)。当你在li-instance中调用changeBusinessIndex()时,它将为businessCtrl1更新currentBusinessIndex,但不会为另一个实例更新。

设置ng-controller =&#34; businessCtrl&#34;在包含li和business-image div的元素上获取控制器的单个实例,如:

<div ng-controller="businessCtrl>
    <li ng-repeat ... etc ></li>
    <div id="business-image" ... ></div>
</div>

答案 1 :(得分:0)

首先,你调用两次ng-controller="businessCtrl"(同名)似乎很奇怪。但是,如果您有兴趣使用两个不同的控制器,我会将currentBusinessIndex存储到服务中并将其用作存储。由于服务是单例,因此您可以将服务注册到两个控制器,这样您的逻辑就可以工作。

<强> HTML

<div ng-controller="MyCtrl_1">
    <button ng-click="showMe();">press  me</button>
    <pre>{{myStorage.getIndex()}}</pre>
</div>

<div ng-controller="MyCtrl_2">
    <pre>{{myStorage.getIndex()}}</pre>
</div>

<强> JS

var myApp = angular.module('myApp', []);

function MyCtrl_1($scope,  myStorage) {   
    $scope.myStorage = myStorage;

    $scope.showMe = function(){
      myStorage.setIndex(3);
    }
}

function MyCtrl_2($scope,  myStorage) {   
    $scope.myStorage = myStorage;    
}


myApp.factory('myStorage', function () {

       var currentBusinessIndex = 0;

       return {
            getIndex: function () {                
               return currentBusinessIndex;
            },
           setIndex: function (index) {
               currentBusinessIndex = index;               
            }
        }
  });

演示 Fiddle