簡體   English   中英

AngularJS var到范圍綁定

[英]AngularJS var to scope binding

我是一個初學者,我認為問題與他們所謂的綁定到原語有關,但我沒有完全掌握這個概念

在我的JS文件中,我有類似以下內容:(請注意,這是半偽代碼!)

var files = [];

function(name){
    files.push({ID: "Three");
}

var writetofile = angular.module("write", []);
writetofile.controller("writeCtrl",  ['$scope', function($scope){
        $scope.allfiles = [{ID: "One"}, {ID: "Two"}];
        $scope.getAllFiles = function(){
            $scope.allfiles.push(files);
        }
$scope.getAllFiles();

在我的HTML文件中:

<ng-controller="writeCtrl">
<div ng-repeat="data in allfiles">
   {{data.ID}}
</div>

本質上,我調用該函數來更新var數組文件,然后將其更新到scope.variable allfiles,並打印出內容。 到目前為止,我可以成功更新文件,但是一旦我推送到所有文件,html上就不會更新。 即使更新后,它也只打印“一個”,“兩個”。

如果我能正確地執行操作,則需要在文件列表上監視$ watch,然后,如果此數組發生更改,則可以更新在HTML中重復的​​列表。 (如果不是同一個$ scope數組!)

但似乎您將對象推到與視圖中的列表不同的列表。 (如果列表相同,則應自行更改)

您要執行的操作對我來說還不是很清楚,我假設您正在嘗試通過將$scope.allFiles列表添加另一個項{ID: "Three"}來更新它。

您應該做的是定義將文件追加到范圍內的allFiles的函數,並將其直接添加到$scope.allFiles

應該是這樣的:

//Inside the controller
$scope.allfiles = [{ID: "One"}, {ID: "Two"}];

$scope.addToFiles = function(fileObj) {
    $scope.allfiles.push(fileObj);
}

$scope.addToFiles({ID: "Three"});

您可以實現,使用concatapplypush作用。 嘗試以下代碼:

 var writetofile = angular.module('write', []); writetofile.controller('writeCtrl', ['$scope', function($scope){ var files = []; function name(){ files.push({ID: "Three"}); } name(); $scope.allfiles = [{ID: "One"}, {ID: "Two"}]; $scope.getAllFiles = function(){ // using concat // $scope.allfiles = $scope.allfiles.concat(files); // using push apply [].push.apply($scope.allfiles, files); } $scope.getAllFiles(); }]); 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app='write' ng-controller="writeCtrl"> <div ng-repeat="data in allfiles"> {{data.ID}} </div> </div> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM