如何在Angular 1.5中使用单向绑定?手表的替代品?

时间:2016-11-15 17:35:09

标签: javascript angularjs angular-components angularjs-1.5

Component.HTML文件:

<div>
  <table class="table table-bordered table-responsive">
  <thead>
<tr>
  <th>Company</th>
  <th>Stock Price</th>
  <th>Last Updated Time</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="list in model.myLists">
  <th>{{list.company}}</th>
  <td>{{list.stockPrice}}</td>
  <td>{{list.lastUpdateTime}}</td>
</tr>
</tbody>
</table>
</div>

这是component.js文件:

(function() {
"use strict";
var module = angular.module("stockdApp");

// Global variables
var stockList = [];

function getStocks (model) {
// api gets stock values every 2 seconds and saves it to stockList variable
stockList = newList;
model.myLists = stockList;
}
function controller($http) {
 var model = this;
 model.$onInit = function() {     
        getStocks(model);            
 } 

 model.$onChanges = function (changes) {
   console.log("channges",changes);        
 };
};

module.component("stocks", {
    templateUrl: "./stock.component.html",
    controllerAs: "model",
    controller: ["$http", controller],
    bindings: {
        myLists: "<"
    }
});
}());

我有一个api调用,它每2秒获取一次新数据,我想在每次获取新数据时更新我的​​表。我正在使用Angular 1.5而不确定如何更新表。

2 个答案:

答案 0 :(得分:1)

当你这样做时

stockList = newList;
model.myLists = stockList;

您正在更改初始数组的引用。 您需要做的是从myList中删除项目并添加新项目,同时保留参考。

这样的事情:

(function() {
"use strict";
var module = angular.module("stockdApp");

function getStocks ($http, model) {
    // Modify to fit your case...
    $http.get(....).then(function(newList) {
        // Empty the array and add the new items while keeping the same refernece
        model.myLists.length = 0;
        newList.forEach(function(newElment) { model.myLists.push(newElment); });
    });
}
function controller($http) {
 var model = this;
 model.myLists = [];

 model.$onInit = function() {     
        getStocks($http, model);            
 } 

 model.$onChanges = function (changes) {
   console.log("channges",changes);        
 };
};

module.component("stocks", {
    templateUrl: "./stock.component.html",
    controllerAs: "model",
    controller: ["$http", controller],
    bindings: {
        myLists: "<"
    }
});
}());

答案 1 :(得分:1)

也许您可以使用 $ scope。$ apply()}

function getStocks (model) {
  $scope.$apply(function(){
   stockList = newList;
   model.myLists = stockList;
 });
}

这样你告诉浏览器模型的内容已经更新。