简体   繁体   English

NG-INIT无法正常工作

[英]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. 我尝试了几种方法,但是由于某种原因,我无法使init方法在正在构建的选项卡应用程序上工作。

I am pulling in JSON using http (via WordPress REST API) and had to use the 'as' syntax to get it working properly. 我使用http(通过WordPress REST API)输入JSON,不得不使用'as'语法使其正常工作。 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 我要初始化的选项卡的menu_order内容为0。在MyData下的ng-inspector中,它显示的是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 . 当前发生的情况是,当UI在页面上呈现时,首先处理ng-init指令,并评估myData.tab = 0并将myDatatab属性值设置为0 Thereafter when asynchronous API completes retrieved data gets assigned to myData object again which wipes out old myData value. 此后,当异步API完成时,检索到的数据将再次分配给myData对象,这将清除旧的myData值。

You shouldn't be using ng-init for this case. 在这种情况下,您不应该使用ng-init You should set data retrieved from ajax to some another property of myData from controller itself. 您应该将从ajax检索到的data设置为控制器本身的myData另一个属性。

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 = {};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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