Angular数组更改时更新HTML视图

时间:2016-04-13 05:34:43

标签: javascript angularjs

在下面的代码中,我更改了数组的第一项中的对象值,但我无法弄清楚如何刷新" HTML视图,以便您在浏览器中看到的内容反映了强制更改。



        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>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:2)

需要从Angular上下文中调用某些内容。 ç

将app.controller部分改为:

app/index.html

和html:

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

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

答案 1 :(得分:1)

您可以使用 ng-init()(native angularjs)代替 onload()(原生javascript)来更改值:

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>