Initializing collapsed state in AngularJS Bootstrap

Reviewing the code provided:

<div class="pull-right text-success m-t-sm">
    <button class="btn btn-default" ng-init="isCollapsed = false" ng-click="isCollapsed = !isCollapsed" data-toggle="tooltip" data-placement="top" title="" data-original-title="See competencies"><i class="fa {{isCollapsed == true ? 'fa-arrow-down': 'fa-arrow-up';}}" ng-click=""></i></button>
</div>

  <div collapse="isCollapsed" class="panel-body collapse" style="height: 0px;">
        <h4>Competencies</h4>

    </div>

The code snippet initializes the variable isCollapsed to false using the ng-init directive.

However, upon running the page, all the boxes appear visible. Any thoughts on the reason for this behavior?

Please note that there is no variable overwriting occurring.

Could lazy loading be a factor? Here's the content of my config.router:

.state('app.competence', {
    url: '/Competence',
    templateUrl: 'tpl/app_competence.html',
    data: {
        authorizedRoles: [USER_ROLES.lb, USER_ROLES.superadmin, USER_ROLES.subadmin]
    },

    resolve: {
        deps: ['$ocLazyLoad',
            function ($ocLazyLoad) {
                return $ocLazyLoad.load(['ngGrid']).then(
                    function () {
                        return $ocLazyLoad.load(['js/controllers/competence/CompetenceController.js','js/controllers/competence/CompetenceUserController.js', 'js/controllers/competence/CompetenceTableController.js', 'js/controllers/headerController.js']);
                    }
                );
            }]
    }
})

HTML scope:

<tab ng-controller="CompetenceUserController as cuCtrl">
    <tab-heading>
        <i class="icon-users text-md text-muted wrapper-sm"></i>Users
    </tab-heading>
    <div class="wrapper-md">
        <div class="row">
            <div class="col-xs-12">
                <div class="panel no-body">
                    <div class="panel-heading wrapper b-b b-light">
                        <input class="form-control" ng-model="search.$" placeholder="Search">
                        <select class="form-control" ng-model="search.competence" ng-options="comp.name "></select>
                    </div>
                    <ul class="list-group">
                        <li class="list-group-item" ng-repeat="user in users | filter:search:strict">
                            <div class="media">
                                <span class="pull-left thumb-sm"><img src="{{user.image_path || 'img/AdamProfil.png'}}" alt="..." class="img-circle"></span>

                                <div class="pull-right text-success m-t-sm">
                                    <button class="btn btn-default" ng-init="init(false)" ng-click="isCollapsed = !isCollapsed" data-toggle="tooltip" data-placement="top" title="" data-original-title="See competencies"><i class="fa {{isCollapsed == true ? 'fa-arrow-down': 'fa-arrow-up';}}" ng-click=""></i></button>
                                </div>
                                <div class="media-body">
                                    <div><a href="">{{user.profile.fullname || user.username}}</a></div>
                                    <small class="text-muted">{{user.title.name}}</small>
                                </div>
                                <div collapse="isCollapsed" class="panel-body collapse" style="margin-top: 10px;">
                                    <h4 class="h4">Competencies</h4>

                                    <div class="table-responsive">
                                        <table class="table table-striped b-t b-light">
                                            <thead>
                                                <th>Competency Name</th>
                                                <th>Level</th>
                                            </thead>
                                            <tbody>
                                                <tr ng-repeat="comp in user.user_competencies">
                                                    <td>{{comp.competency.name}}</td>
                                                    <td>{{comp.competency_level_id}}</td>
                                                </tr>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </li>
                    </ul>
                </div>
            </div>
        </div>
    </div>
</tab>

My controller:

app.controller('CompetenceUserController', ['$http', '$scope', '$sessionStorage','competenceService', '$log', 'Session', 'api', function ($http, $scope, $sessionStorage, $log, Session, api, competenceService) {
    $scope.init = function(value) {
        $scope.isCollapsed = value;
    };
    $scope.competencies = [];
    competenceService.getRawList().then(function(response)
    {
        $scope.competencies = response;
    });
    $scope.users = [];
    $http.get(api.getUrl('userCompetence', null)).success(function (response) {
        $scope.users = response;
    });
}]);

Answer №1

The reason is that you are setting the isCollapsed variable to false instead of true.

Answer №2

Make sure to initialize the isCollapsed variable before assigning a value of false. ng-init="isCollapsed = false"

In my opinion, it is better to call a function to set the variable value.

  <button class="btn btn-default" ng-init="init(false)" ng-click="isCollapsed = !isCollapsed" data-toggle="tooltip" data-placement="top" title="" data-original-title="Se kompetencer"><i class="fa {{isCollapsed == true ? 'fa-arrow-down': 'fa-arrow-up';}}" ng-click=""></i></button>

In the controller

 $scope.init = function(value) {
    $scope.isCollapsed = value;
  }

You can also directly assign the value

$scope.isCollapsed = false;

in the controller.

Answer №3

It seems that the issue may not be related to lazy loading, but rather the fact that the variable isCollapsed is not accessible within the specific scope you are trying to reference.

To ensure its accessibility, consider encapsulating it within an object (and potentially defining your ng-init at a higher level in the hierarchy).

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I keep encountering an error stating that parameter 1 for 'FormData' is not of type 'HTMLFormElement'. I am struggling to resolve this issue on my own. Can someone please assist me with fixing this problem?

Here is the snippet of code that I am struggling with: const authForm = useRef(); const handleSubmit = (e) => { e.preventDefault(); //formData let form = new FormData(authForm.current); console.log(form) } This code snippet shows how I added a ...

Adjusting the position of an iframe with a YouTube video when the window is resized

I'm struggling with resizing and moving a YouTube video embedded using the Youtube API. I'm not a web designer, so I'm facing some difficulties. When trying to resize the window, I can't seem to move or resize the video within an iframe ...

Why isn't $.post functioning properly in any instance?

I've been experiencing issues with my $.post calls throughout my code. Despite not sending requests to different domains, everything is localhosted. My Mac OS X 10.8 automatically defined my localhost alias as ramon.local, and I'm trying to make ...

Prevent selection of rows in the initial column of DataTables

I am working on a basic datable, the code can be found here JS: var dataSet = [ ["data/rennes/", "Rennes", "rennes.map"], ["data/nantes/", "Nantes", "nantes.map"], ["data/tours/", "Tours", "tours.map"], ["data/bordeaux/", "Bordeaux", ...

Discover the new features of Next.js 13: Learn how to efficiently extract parameters from URLs using userParams, and seamlessly pre-render components at build time

Currently, I am diving into the latest version of next.js 13.4 and have set up a page with the route /notes/[note]. To extract the note parameter from the URL, I am utilizing import { useParams } from 'next/navigation'. In addition to this, I wa ...

How to incorporate a routing file within another routing file in Node.js

I have structured my routes as follows: / /business /business/stuff1 /business/stuff2 /business/admin For /business, I am using a separate file for the routing and functions. And similarly, for /business/admin, I also want to use a separate file f ...

Removing all comments from a post that has been deleted in MongoDB

I am currently following the MEAN stack tutorial provided by Thinkster () and I have encountered an issue with implementing delete operations. Here are the schemas I am working with: var PostSchema = new mongoose.Schema({ title: {type: String, required ...

By changing the name of my file to .js.erb, I am able to seamlessly incorporate erb syntax within my javascript code, but this

Currently, I am using chessboard-0.3.0.js in a rails application. Due to the rails asset pipeline setup, I've had to make adjustments to the js code specifically related to rendering images, such as Pieces. In line 445 of chessboard.js, it states: c ...

Determine if offcanvas element is visible upon initialization in Bootstrap 5 Offcanvas

I have a search-filter offcanvas div for location and property type on this webpage: On larger screens (desktop), the offcanvas is always visible, but on smaller screens (mobile), it is hidden and can be toggled with a button. This functionality works per ...

Maintaining the selected option on page refresh with React Remix

I have a dropdown menu with 2 choices (en, no) for switching the language when onChange event occurs. To save the selected language, I am using localStorage. Due to the server-side rendering in Remix, direct access to localStorage is not possible. Therefo ...

The logout confirmation message functionality in Laravel 8 is malfunctioning

In my Laravel project, I am attempting to implement a logout confirmation message that will pop up when a user clicks on the logout button. Here is the code I have added to my navbar.blade.php: <a class="dropdown-item" id="logout" hr ...

Concern with Isotope's masonry feature

I'm at my wit's end! The container div I'm dealing with is 1170px wide. My goal is to fit in 3 divs within this width. The first div is 275px wide, the second is 580px wide, and the third is also 275px wide. Altogether, these divs should ad ...

Ways to avoid caching statically generated pages without having to enable ISR in Next.js

I'm currently exploring ways to tailor the Cache-Control headers for my NextJS server when delivering pages generated at build time (SSG). The objective is straightforward: since every CDN caches server responses based on their headers, and I want sta ...

What are the steps for modifying the JSON data format in AngularJS?

As a newcomer to Angular JS, I am working with the following JSON data: { "CheckList": [ { "UnitClass": "Budget Space", "CheckListCategoryId": 1, "CheckListCategory": "DOORS", "CheckListItemId": 2, "CheckListItem": "Deadbolt, Lockse ...

Cannot assign type void to 'Intrinsic Attributes & Dispatch<SetStateAction<>>'

Just starting out with typescript and ran into this error: Error :Type '{ setTasks: void; }' is not assignable to type 'IntrinsicAttributes & Dispatch<SetStateAction<IStudy[]>>'. Property 'setTasks' does not e ...

An error occurred while attempting to create-react-app, with the message "npm ERR! cb() never called!" popping up during the process

Encountering difficulties when attempting to create a React app PS D:\Projects\Test> npx create-react-app my-app Creating a new React app in D:\Projects\Test\my-app. Installing packages. This may take a few minutes. Installing ...

Using $stateParams injection for unit testing Angular applications with Karma

Here is the starting point for the controller code: angular .module('hc.hotelContent') .controller('NameLocationController', nameLocationCtrlFn); //Todo change hotelDataService nameLocationCtrlFn.$inject = ['$stateParams', &a ...

What is the solution to preventing Angular 1.3 ngMessages from affecting the size of my form?

Hey there, I'm diving into front-end design for the first time. My issue is with a form that I want to use ng-messages for validation error messages. Currently, my form's size changes depending on whether there are errors displayed or not, and it ...

Creating interfaces for applications that are driven by events in JavaScript

When it comes to designing an application, traditional UML Class diagrams may not always be useful, especially for programs that do not heavily rely on classes. For instance, in a JavaScript application that is mainly event-driven, where you listen for eve ...

Is it feasible to place an ordered list within a table row <tr>?

Below is a code snippet demonstrating how to create an ordered list using JavaScript: Here is the JavaScript code: <script type="text/javascript"> $(document).ready(function() { $("ul").each(function() { $(this).find("li").each(functio ...