Time to paint angularjs menu

2019-09-05 02:16发布

问题:

I have a menu that I walk with a "ng-repeat" to paint the problem that I have is that if you burn a variable with the json from the menu that is painted correctly, but if the menu as consumption from a WebAPI not paint me complete, menu is as if first paint the html consultation before the end of the WebAPI. The menu paints me correctly, but a submenu (dropdown) does not paint me children.

They know how to solve it?

This is the menu

This is the html

<div ng-controller="dashboardController" class="nav-wrapper">
    <ul ng-init="menuApp()">
      <li ng-repeat="item in menus" ng-init="$last && rebindDropDowns()" class="{{item.Submenu.length ? 'dropdown-button' : ''}}" ng-bind-html="item.Nombre" data-activates="{{item.Submenu.length ? 'administracion' : ''}}">
        {{item.Opcion}}
        <ul ng-if="item.Submenu.length>0" id="administracion" class="dropdown-content">
          <li ng-repeat="subItem in item.Submenu"><a ng-href="{{subItem.Nombre}}">{{subItem.Descripcion}}</a></li>
        </ul>
      </li>
    </ul>
  </div>

And this is the Controller

(function() {
  'use strict';
  angular.module('gastosDeViaje').controller('dashboardController', ['$scope', 'dashboardService', 'accesoService', 'notificaService', 'legalizacionService', '$location', '$q',
    function($scope, dashboardService, accesoService, notificaService, legalizacionService, $location, $q, men) {
      $scope.menuApp = function() {
        accesoService.consultaMenu(accesoService.authentication.userName).then(function(result) {
          $scope.menus = result.data;
          console.log(result);
        });
      };
      $scope.rebindDropDowns = function() {
        console.log('entro drop');
        $('.dropdown-button').dropdown();
      };
      $scope.menu = [{
        "Opcion": "Solicitud",
        "Nombre": "<a href=\"#/solicitud\"><i class=\"material-icons left\">flight</i>Solicitud</a> ",
        "Descripcion": "Formulario para Solicitud",
        "Submenu": []
      }, {
        "Opcion": "Consultas",
        "Nombre": "<a href=\"#/consulta\"><i class=\"material-icons left\">search</i>Consultas</a> ",
        "Descripcion": "Formulario para Consultas",
        "Submenu": []
      }, {
        "Opcion": "Transferencia",
        "Nombre": "<a href=\"#/transferencia\"><i class=\"material-icons left\">attach_money</i>Transferencia</a> ",
        "Descripcion": "Transferencia",
        "Submenu": []
      }, {
        "Opcion": "Administracion",
        "Nombre": "<a class=\"dropdown-button\" data-activates=\"administracion\"><i class=\"material-icons left\">settings</i>Administracion<i class=\"material-icons right\">arrow_drop_down</i></a> ",
        "Descripcion": "Menu de Administracion",
        "Submenu": [{
          "Opcion": "Reservas",
          "Nombre": "#/reservas ",
          "Descripcion": "Reservas",
          "Submenu": null
        }, {
          "Opcion": "Globales",
          "Nombre": "#/globales ",
          "Descripcion": "Globales",
          "Submenu": null
        }, {
          "Opcion": "Convenios",
          "Nombre": "#/convenios ",
          "Descripcion": "Convenios",
          "Submenu": null
        }, {
          "Opcion": "Aplicacion",
          "Nombre": "#/aplicacion ",
          "Descripcion": "Aplicacion",
          "Submenu": null
        }]
      }];
      dashboardService.getEmpleadoAprobar(accesoService.authentication.userName).then(function(results) {
        $scope.empleadosAprobar = results.data;
      }, function() { //error
        console.log('Error al Cargar los datos');
      });
      dashboardService.getEmpleadoAutorizar(accesoService.authentication.userName).then(function(results) {
        $scope.empleadosAutorizar = results.data;
      }, function() { //error
        console.log('Error al cargar las autorizaciones');
      });
      dashboardService.getEmpleadolegalizar(accesoService.authentication.userName).then(function(results) {
        $scope.empleadoLegalizar = results.data;
      }, function() { //error
        console.log('error al consultar');
      });
      dashboardService.getEmpleadoPdtLegalizarSub(accesoService.authentication.userName).then(function(results) {
        $scope.PdtLegalizarSub = results.data;
      }, function() {
        console.log('Error al traer los pdtes por Legalizar');
      });
      dashboardService.getLegPdtAutorizar(accesoService.authentication.userName).then(function(result) {
        $scope.LegPdtAutorizar = result.data;
      }, function(error) {
        console.log(error);
      });
      dashboardService.getLegPdtAprobar(accesoService.authentication.userName).then(function(result) {
        $scope.LegPdtAprobar = result.data;
      }, function(error) {
        console.log(error);
      });
      dashboardService.getEmpleado(accesoService.authentication.userName).then(function(result) {
        $scope.Nombre = result.data.Nombre;
      }, function(error) {
        if (!angular.isUndefined(error)) {
          angular.forEach(error.data.ModelState.Model, function(errores) {
            notificaService.error(errores);
          });
        }
      });
      dashboardService.solicitudesActivasEmpleado(accesoService.authentication.userName).then(function(result) {
        $scope.solActivas = result.data;
      });
      /*$scope.solicitudesActivasEmpleado = function(){
    console.log('entro activas');

    $scope.pagActual = 0;
    $scope.pageZise = 3;

    $q.all([
      dashboardService.solicitudesActivasEmpleado(accesoService.authentication.userName)
    ]).then(function(results){
      $scope.solActivas = results[0].data;
      $scope.numPaginas = function(){
        return Math.ceil($scope.solActivas.length / $scope.pageZise);
      };
    }, function(error){
      console.log(error);
    });
  };*/
      $scope.CambiaEstadoSol = function(id, documento, estado) {
        var parametros = '?id=' + id + '&documento=' + documento + '&estado=' + estado + '&funLog=' + accesoService.authentication.userName;
        dashboardService.putCambiaEstadoSol(parametros).then(function() { //results
          $location.path('#/dashboard'); //Lo hago para que me actualice la lista de pendientes x aprobar
          if (estado === 'A') {
            notificaService.success('Solicitud Aprobada Exitosamente');
          }
          if (estado === 'T') {
            notificaService.success('Solicitud Autorizada Exitosamente');
            /*if (documento==='L') {
              //legalizacionService.postLegalizarAndres
            }*/
          }
          if (estado === 'N') {
            notificaService.success('Solicitud Anulada Exitosamente');
          }
        }, function(error) {
          error.data.ModelState.Model.forEach(function(data) {
            notificaService.error(data);
          });
        });
      };
      $scope.VerSolicitud = function(id) {
        $location.path('/solicitud/' + id);
      };
      $scope.LegalizarSolicitud = function(id) {
        $location.path('/legalizacion/' + id + '/' + 'L');
      };
      $scope.CambiaEstadoLeg = function(id) {
        $location.path('/legalizacion/' + id + '/' + 'A');
      };
    }
  ]);
  angular.module('gastosDeViaje').filter('paginacion', function() {
    return function(input, start) {
      if (!input || !input.length) {
        return;
      }
      start = +start;
      return input.slice(start);
    };
  });
})();

回答1:

The problem seems to be on $('.dropdown-button').dropdown(); that is called from template in <li ng-repeat="item in menus" ng-init="$last && rebindDropDowns()"... but I can't simulate this issue.

It happens because ng-init is running before render html on DOM. Then when you apply jQuery plugin, the element doesn't exists yet.

By the way, using jQuery inside controller is not a good idea at all.

UPDATE 1

Try using a directive to initialize jQuery plugins like so:

angular.module('gastosDeViaje').directive('dropdownButton', 
    function() {
      return {
        restrict: 'EAC',
        link: function($scope, element, attrs, controller) {

            jQuery(element).dropdown();
        }
      };
    }
  );

This will apply directive for the class .dropdown-button.



回答2:

I made this change and it worked: D

<div ng-controller="dashboardController" class="nav-wrapper">
   <ul ng-init="menuApp()">
     <li ng-repeat="item in menus" class="{{item.Submenu.length ? 'dropdown-button' : ''}}" ng-bind-html="item.Nombre" data-activates="{{item.Submenu.length ? 'administracion' : ''}}">
{{item.Opcion}}
<ul ng-if="item.Submenu.length>0" id="administracion" class="dropdown-content">
    <li ng-repeat="subItem in item.Submenu" ng-init="$last && rebindDropDowns()">
    <a ng-href="{{subItem.Nombre}}">{{subItem.Descripcion}}</a>
    </li>
    </ul></li></ul></div>