简体   繁体   中英

NG-INIT not working properly

I have tried several ways, but for some reason, I am not able to get the init method to work on a tab application I am building.

I am pulling in JSON using http (via WordPress REST API) and had to use the 'as' syntax to get it working properly. Everything works once I click the initial tab, but I need the first tab to load on page load.

Here is the App:

 JS: var homeApp = angular.module('homeCharacters', ['ngSanitize']); homeApp.controller('characters', function($scope, $http) { $http.get("http://example.com/wp-json/posts?type=character").then(function(response) { $scope.myData = response.data; }); }); homeApp.filter('toTrusted', ['$sce', function($sce) { return function(text) { return $sce.trustAsHtml(text); }; } ]); 
 HTML: <section class="characters" ng-app="homeCharacters" ng-controller="characters as myData"> <div class="char_copy" ng-repeat="item in myData" ng-bind-html="item.content | toTrusted" ng-show="myData.tab === item.menu_order"> {{ item.content }} </div> <div class="char_tabs"> <nav> <ul ng-init="myData.tab = 0"> <li ng-repeat="item in myData"> <a href ng-click="myData.tab = item.menu_order"> <img src="{{ item.featured_image.source }}" /> <h3>{{ item.title }}</h3> </a> </li> </ul> </nav> </div> </section> <!--end characters--> 

I am assuming there is something simple I am missing. The menu_order content for the tab I want to init is 0. In ng-inspector under MyData it shows tab : 0

I would appreaciate any help anyone could offer!

Currently what happening is when UI gets rendered on page, ng-init directive gets processed first and it evaluates myData.tab = 0 and set myData 's tab property value to 0 . Thereafter when asynchronous API completes retrieved data gets assigned to myData object again which wipes out old myData value.

You shouldn't be using ng-init for this case. You should set data retrieved from ajax to some another property of myData from controller itself.

Code

homeApp.controller('characters', function($scope, $http) {
  $scope.myData = { tab: 0 }; //set default tab
  $http.get("http://example.com/wp-json/posts?type=character").then(function(response) {
    $scope.myData.data = response.data;
  });
});

Markup

<li ng-repeat="item in myData.data">

在调用服务之前,您只需要声明您的作用域为emoty对象或null即可,它将像下面这样工作:$ scope.myData = {};

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