为什么AngularJS ng-bind没有更新推送数组

时间:2017-05-18 05:07:27

标签: javascript angularjs

我正在尝试将字符串推入数组并在视图中实时更新。它正在表达但不在ng-bind中工作。请帮我找出原因?

HTML:

<div ng-app=“app”>
        <div ng-controller="testController">
           <div ng-bind="fruit"></div>
           <div>{{fruit}}</div>
           <button ng-click="add()">add</button>
       </div>
   </div>

控制器:

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

app.controller('testController', ['$scope', function($scope){
    $scope.fruit = ['apple'];

    $scope.add = function() {
        var a = 'banana';
        $scope.fruit.push(a);
    };
}]);

2 个答案:

答案 0 :(得分:0)

使用ng-repeat打印数组中的所有值

&#13;
&#13;
routegroup
&#13;
var app = angular.module('app', []);

app.controller('testController', ['$scope', function($scope){
    $scope.fruit = ['apple'];

    $scope.add = function() {
        var a = 'banana';
        $scope.fruit.push(a);
    };
}]);
&#13;
&#13;
&#13;

答案 1 :(得分:0)

ng-bind无效,因为您在角度应用的fruit周期之外更改了digest的值。

要更新ng-bind中的变量,请使用$scope.apply()

您也可以按照sumit chauhan的建议使用ng-repeat

<强>样本

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

myApp.controller('MyCtrl', function($scope, $interval) {
    $scope.fruit = ['apple'];

    $scope.add = function() {
       var a = 'banana';
       $scope.fruit.push(a);
    };
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
  <button ng-click="add()">add</button>
  <div ng-repeat="item in fruit track by $index">
    {{item}}
  </div>
</div>
&#13;
&#13;
&#13;