ng-show не работает angular.js

0

Я пытаюсь скрыть и показать содержимое в определенном div в моем html для всплывающего окна.

home.html

 <div role="main" class="container theme-showcase">
      <div class="" style="margin-top:90px;">
        <div class="col-lg-8">
            <div class="page-header">
                <h2 id="tables">Search people</h2>
            </div>
            <div class="bs-component" ng-controller="homeCtrl">
                <div class="alert alert-info" ng-hide=true>
                    <p>Sort key: {{sortKey}}</p>
                    <p>Reverse: {{reverse}}</p>
                    <p>Search String : {{search}}</p>
                </div>
                <form class="form-inline">
                    <div class="form-group">
                        <label >Search</label>
                        <input type="text" ng-model="search" class="form-control" placeholder="Search">
                    </div>
                </form>
                        <table class="table table-striped table-hover">
                            <thead>
                              <tr>
                                <th>
                                <span></span>
                          </th>
                            <th ng-click="sort('firstName')">First Name
                            <span class="glyphicon sort-icon" ng-show="sortKey=='firstName'" ng-class="{'glyphicon-chevron-up':reverse,'glyphicon-chevron-down':!reverse}"></span>
                           </th>
                           <th ng-click="sort('lastName')">Last Name
                               <span class="glyphicon sort-icon" ng-show="sortKey=='lastName'" ng-class="{'glyphicon-chevron-up':reverse,'glyphicon-chevron-down':!reverse}"></span>
                           </th>
                               <th ng-click="sort('profession')">Job Title
                                  <span class="glyphicon sort-icon" ng-show="sortKey=='profession'" ng-class="{'glyphicon-chevron-up':reverse,'glyphicon-chevron-down':!reverse}"></span>
                             </th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr ng-click="showModal($event, user.emailAddress)" dir-paginate="user in users|orderBy:sortKey:reverse|filter:search|itemsPerPage:5">
                                    <td ><img src = {{user.profileImageUrl}} width="100" height="100"><img></td>
                                    <td>{{user.firstName}}</td>
                                    <td>{{user.lastName}}</td>
                                    <td>{{user.profession}}</td>
                                </tr>
                            </tbody>
                        </table> 

                    </div>
                <dir-pagination-controls
                    max-size="5"
                    direction-links="true"
                    boundary-links="true" >
                </dir-pagination-controls>
            </div>

            <!-- start -->

        <div class="panel-heading">

        <div ng-show="showAlert" >
          <div ng-include="'views/alert.html'"></div>
        </div>



        </div>
      </div>
    </div>

всплывающие данные, вызываемые из home.html

  <div ng-show="showAlert" >
          <div ng-include="'views/alert.html'"></div>
        </div>

alert.html

<div class="modal fade in" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" style="display: block; padding-right: 15px;" >
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header" style="height: 3em;">
        <button type="button" ng-click="closeModal()" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>

      </div>
      <div class="modal-body">
<div ng-show="showDetails">
        <div><h3 class="text-danger">Job Title</h3></div> <!-- ithink you can change it-->
        <div><span class="genericText">{{alert.profession }}</span></div>
        <div class="genericText"><h3 class="text-danger">Approved Organisation</h3><div>
        <div><span class="genericText">{{alert.organisation}}</span></div>
          <div><h3 class="text-danger">Department</h3></div>
        <div><span class="genericText">{{alert.department}}</span></div>
      </div>     
    </div>
    <div style="text-align:center; padding-top:2em" >
    <button type="button" ng-click="showRequestForm()" class="btn btn-default">Request Person</button>
  </div>
</div>


      <!-- FORM -->
    <!-- pass in the variable if our form is valid or invalid -->
    <form name="requestForm" style="text-align:center" ng-submit="requestForm(requestForm.$valid)" novalidate> <!-- novalidate prevents HTML5 validation since we will be validating ourselves -->

        <!-- EMAIL -->
        <div id='genericText' style="display:inline-block; vertical-align:top;" class="form-group" ng-class="{ 'has-error' : requestForm.email.$invalid && !requestForm.email.$pristine }">
            <input type="text" name="email" style="width:20em; height:3em; border-radius:0px" class="form-control" placeholder="Email Address" ng-model="email" required>
            <!-- !loginForm.email.$pristine == false has not been used yet !-->
            <p ng-show="requestForm.email.$invalid && !requestForm.email.$pristine" class="help-block">Enter a valid email</p>
        </div>

        <br>
        <!-- SUBMIT BUTTON -->
        <button type="submit" id='submitButton' class="btn btn-primary" ng-disabled="requestForm.$invalid">Send Request</button>

    </form>


            <!-- end -->

        </div>
      </div>
    </div></div></div></div></div>
</div>

Наконец, код для контроллера home.js

<div ng-show="showDetails">

home.js

     'use strict';

//app global variable
//this is the controller that handles post requests
//declare services as dependecies $http, $location, custom service apiServiceWeb
app.controller('homeCtrl', function($scope, $http, $cookies, $rootScope, $location, loggedInStatus, setCredentials, apiServiceWeb) {


  //get cookie, and then make api call
  var cookieData = setCredentials.getCookie('globals');

  console.log(cookieData);
  console.log("email " + cookieData.auth.username);
  console.log("userType " + cookieData.auth.userType);
  console.log("token " + cookieData.auth.token);

  var ctr_scope = $scope;
  $scope.users = []; //declare an empty array

  $scope.alert = {};
  $scope.showAlert = false;
  $scope.users = [{
    "busy": false,
    "emailAddress": "test@test",
    "userType": "test",
    "title": "test",
    "firstName": "test",
    "lastName": "test",
    "dob": "tset",
    "profession": "test",
    "jobTitle": "test",
    "profileImageUrl": "test.jpg"
  }];

  $scope.sort = function(keyname) {
    $scope.sortKey = keyname; //set the sortKey to the param passed
    $scope.reverse = !$scope.reverse; //if true make it false and vice versa
  }

  /*$scope.test = function(text) {
    alert(text);

    //go to persons profile page
  }*/

  $scope.showModal = function(event, id) {


    //get object
    var user = $scope.users.filter(function(o) {
      return o.emailAddress == id
    })

    if (user[0]) {
      $scope.$parent.alert.profession = user[0].profession;
      $scope.$parent.alert.department = user[0].jobTitle;
      $scope.$parent.alert.organisation = 'test';

    }
    console.log($scope);
    $scope.$parent.showAlert = true;
    $scope.showDetails = false;

  };

  $scope.closeModal = function() {
    $scope.showAlert = false;
  };


  $scope.showRequestForm = function(){

    //show request form

  };

});

я пытался

$scope.$parent.showDetails = true;

а также

$scope.showDetails = true;

и все же он показывает пустое всплывающее окно и не может обнаружить между состояниями.

Любая идея, почему это происходит, спасибо

  • 1
    Добавьте полный код вашего homeCtrl , который поможет диагностировать.
  • 0
    отредактировал код для вас

2 ответа

-1

Вы должны использовать угловую версию загрузочного модального https://angular-ui.github.io/bootstrap/#/modal

  • 0
    У меня возникают проблемы с пониманием того, почему использование JQuery в angularJS является лучшей идеей, чем использование угловой версии компонента.
  • 0
    Это не проблема здесь, я думаю, что ваш ответ не отвечает на его проблему / вопрос, а просто ссылается на другую библиотеку.
-2

Ваше ng-шоу, скорее всего, работает нормально. Тем более, что вы указываете, что он просто показывает пустой div. Я думаю, ваша проблема здесь в том, что вы включаете в себя загрузочный модальный, который по умолчанию будет скрыт.

Попробуйте удалить ng-show, которое обертывает ваш ng-include для 'views/alert.html'

Используйте Javascript для запуска show modal:

$('#myModal').modal('show')
  • 0
    Вы не должны использовать JQuery в angular ... По крайней мере, поместите этот код в директиву и используйте angular.element вместо $ ('# mymodal')
  • 0
    Справедливо по поводу использования Jquery в angular, моё предлагаемое решение было просто подтвердить, откуда возникла его проблема. Также обратите внимание, что angular.element - это просто псевдоним для функции jQuery.

Ещё вопросы

Сообщество Overcoder
Наверх
Меню