-1

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>
Daniel Williams
  • 2,195
  • 7
  • 32
  • 53

2 Answers2

2

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()">
Nirav Ranpara
  • 13,753
  • 3
  • 39
  • 54
Gene
  • 616
  • 4
  • 8
  • 1
    Your solution can't work. **box.changeSomething()** can't be recognized by **onload** event. Instead use **ng-init** there. – Ganesh Matkam Apr 13 '16 at 06:06
  • It's not a solution but a hint at what is wrong. Create a plunker and I'll take a look. – Gene Apr 13 '16 at 08:07
1

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>
Theo Itzaris
  • 4,321
  • 3
  • 37
  • 68