简体   繁体   中英

Updating HTML view when Angular array changed

In my code below I change an object value in the array's first item, but I am having trouble figuring out how to "refresh" the HTML view so that what you see in the browser reflects the forced change.

  var dataArray = [{ name: 'fax.doc', size: 100, }, { name: 'fax.pdf', size: 110, }, { name: 'fax.xls', size: 120, }]; (function() { var app = angular.module('myApp', []); app.controller('AppController', function() { this.files = dataArray; }); })(); function changeSomething() { dataArray[0].name = "facsimile.doc"; // alert(dataArray[0].name); } 
  <!doctype html> <html ng-app="myApp"> <head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> </head> <body ng-controller="AppController as box" onload="changeSomething()"> <table border="1"> <tr ng-repeat="file in box.files"> <td>{{file.name}}</td> <td>{{file.size}} bytes</td> </tr> </table> </body> </html> 

Something needs to be called from within the Angular context. C

hange the app.controller part to be:

 app.controller('AppController', function() {
     this.files = dataArray;

     this.changeSomething = function() {
         dataArray[0].name = "facsimile.doc";
         alert(dataArray[0].name);
     };
 });

and the html to be:

<body ng-controller="AppController as box" ng-init="box.changeSomething()">

Instead of onload() (native javascript) you can use ng-init() (native angularjs) , to change the values :

CONTROLLER(your function into the controller):

app.controller('AppController', function() {
              var vm = this;
                vm.files = dataArray;

                vm.changeSomething= function() {
                  vm.files[0].name = "facsimile.doc";
                   alert(dataArray[0].name);
                 };
        });

HTML

<body ng-controller="AppController as box" ng-init="changeSomething()">
    //your code here 
</body>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM