AngularJS:如何在间隔后执行ng-init

时间:2016-04-27 13:13:53

标签: javascript html angularjs

我正在从谷歌电子表格中将对象加载到一个数组中。但是当我想在页面加载时自动显示这些对象时。问题是加载这些对象需要一秒钟或2秒。所以我的页面在初始化完成之前已完全加载。这样它就不会显示对象,直到我再次调用控制器。所以我的问题是:在初始化完成后我可以使用ng-init调用函数吗?

初​​始化:

this.partsInit = function(){
        jQuery.getJSON(this.ssl).success(function(data) {

            for (var i = 0; i < data.feed.entry.length; i++) {
                var id = data.feed.entry[i].gsx$id.$t;
                var name = data.feed.entry[i].gsx$name.$t;
                var price = data.feed.entry[i].gsx$price.$t;
                var notcompatiblewith = data.feed.entry[i].gsx$notcompatiblewithkommagescheiden.$t;
                var img = data.feed.entry[i].gsx$img.$t;
                var comp = notcompatiblewith.split(",")

                $rootScope.parts.push({"id": parseInt(id), "name": name, "price": parseInt(price), "comp": comp, "img": img, "canAdd": true, "added": false});
            };
        });
    };

ssl等于:'https://spreadsheets.google.com/feeds/list/1l4XTKaLZihj5WDRuZJE5Y7RQ7Cr7SD_-tH0ctwhizWc/od6/public/values?alt=json'

HTML:

<div class="someName" ng-init="pl.partsInit()">
<ul class="plist">
        <li ng-repeat="part in pl.parts | orderBy:'+price'" ng-hide="part.added || !part.canAdd" class="plLi">
            <div class="plistDivName">
                {{part.name}}   <!--alternatief: -->
            </div>
            <div>
                <img src="{{part.img}}" class="listIMG"></img>
            </div>
            <div>
                {{part.price | currency : "&euro;"}} <!-- | currency om 2 cijfers na de komma te krijgen -->
            </div>
            <div class="plistDivButton">
                <button ng-click="pl.ap = pl.ap + 1; pl.jadd(part.id); pl.stillPossible(part.id)" ng-show="part.canAdd" class="addButton">+</button> <!-- veranderd value van pl.parts.added naar true -->
            </div>
        </li>
    </ul>
 </div>

1 个答案:

答案 0 :(得分:0)

以下是您可以根据需要修改的模板代码。

// at the bottom of your controller
var init = function () {
   // ---------- Your Code ----------

};
// and fire it after definition
init();

另外,您可以查看ng-init指令。实施将非常像:

// register controller in html
<div data-ng-controller="myCtrl" data-ng-init="init()"></div>

// in controller
$scope.init = function () {
   // ---------- Your Code ----------
};

当我想将值从后端传递到angular app时,我使用了ng-init:

<div data-ng-controller="myCtrl" data-ng-init="init('%some_backend_value%')"></div>