Unable to navigate using ui-sref or $state.go in initial directive execution

There seems to be an issue with my ng-repeat on a directive where I'm passing in 3 pieces of information. The directive includes a button that is supposed to pass that information on to another view using params like this:

ui-sref='profiles.show({userId:profile._id, index:index, list:list})

Oddly enough, all the buttons for the cards (which are essentially the directives) work properly, except for the one at index 0. For some reason, the button at index 0 fails to trigger a ui-sref or a $state.go. I even tried setting it up with an ng-click and encountered a strange outcome where the console log successfully displayed the correct data, but the $state.go with the params did not execute.

$state.go('profiles.show', {userId: profile._id, index: index, list: list})

In an attempt to troubleshoot, I noticed that removing the index and the list from the params allowed the ui-sref or $state.go to work for the first element again. However, this caused issues in the subsequent view as it lacked the necessary information.

Here is the state config for profiles.show

.state('profiles.show', {url: '/{userId}', params: { index: null, list: null }, templateUrl:'/views/profiles/show/show.html', controller: 'ProfilesShowController'})

Below is the ng-repeat (written in Jade):

.text-capitalize(al-card, ng-repeat='profile in profiles | filter:searchBar track by $index', profile='profile', index='$index', list='profiles')

Here is the button with the ng-click event

button.btn.btn-default(ng-click='goToProfile(profile, index, list)') Learn More

And here is the $scope function defined:

$scope.goToProfile = function(profile, index, list) {
  console.log(profile);
  console.log(index);
  console.log(list);
  $state.go('profiles.show', {userId: profile._id, index: index, list: list});
};

Any assistance with this dilemma would be greatly appreciated.

Answer №1

One issue that was brought up by @KevinF was that index 0 was mistakenly being considered a false value. To fix this issue, I made a simple adjustment to this specific line of code:

.text-capitalize(al-card, ng-repeat='profile in profiles | filter:searchBar track by $index', profile='profile', index='$index', list='profiles')

changed to:

.text-capitalize(al-card, ng-repeat='profile in profiles | filter:searchBar track by $index', profile='profile', index='$index.toString()', list='profiles')

Additionally, within the directive, I simply reassigned it to itself using parseInt($index)

Answer №2

Check out my Plunkr example. It seems to be functioning fine with index 0, so I'm not certain if the issue lies with the index variable. Can you spot any differences in my code aside from the filtering? I suspect that the filtering could be causing the problem.

http://plnkr.co/edit/lhU8A3rhUR0JLw5KCNQM

<!DOCTYPE html>
<html ng-app="Test">

  <head>
    <script data-require="angular.js@~1.4.0-rc.2" data-semver="1.4.0-rc.2" src="https://code.angularjs.org/1.4.0-rc.2/angular.js"></script>
    <script data-require="ui-router@*" data-semver="0.2.15" src="//rawgit.com/angular-ui/ui-router/0.2.15/release/angular-ui-router.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body>
    <div ui-view></div>
  </body>

</html>
-------------------------------------------
<div ng-controller="SelectProfile">
  <button ng-repeat="profile in profiles track by $index" 
  ui-sref="profile({userId: profile.userId, index: $index})">
    {{ profile.userId }}
  </button>
</div>
----------------------------------------------
<div ng-controller="Profile">
  {{ profile.userId }}
  <br>
  {{ profile.index }}
</div>

<a ui-sref="home">home</a>
-----------------------------------------------
(function(){
  angular.module('Test', ['ui.router']);

  angular.module('Test')
    .run(function($rootScope, $state, $stateParams){
      $rootScope.$state = $state;
      $rootScope.$stateParams = $stateParams;
    });

  angular.module('Test')
    .config(function($stateProvider, $urlRouterProvider){
      $urlRouterProvider.otherwise('/');

      $stateProvider
            .state('home', {
                url: '/',
                templateUrl: 'home.html'
            })
            .state('profile', {
              url: '/:userId',
              params: {
                index: null,
                list: null
              },
              templateUrl: 'profile.html'
            });
    });

  angular.module('Test')
    .controller('SelectProfile', function($scope){
      $scope.profiles = [
        {userId: 1},
        {userId: 2},
        {userId: 3}
      ];
    });

  angular.module('Test')
    .controller('Profile', function($scope, $rootScope){
      $scope.profile = {
        userId: $rootScope.$stateParams.userId,
        index: $rootScope.$stateParams.index
      };
    });
})();

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

Utilizing the classList property with elements that are hidden from view

How can I use JavaScript to toggle between classes? I can't seem to understand why an element that is set to display: none; is unable to receive a class using classList. In simpler terms, if I define #div1{ width: 25%; background-color: #000000; ...

I encountered a problem with iteration where the results appeared perfectly fine, but upon rendering at the component level, the same field loaded with the last object instead

I am facing an issue with rendering the component level when it loads. After clicking on edit and calling the edit function, the data is properly loaded in console and all objects are shown. However, they do not render on the page level. Below is the code ...

JSON data converted into an adjacency list

I am attempting to programmatically create a new object in the form of an adjacency list using the provided sampleData. This object will be used in jointJS to generate an organization chart: sampleData = [ {"id":"1224286", "label":"someLabel1", "image ...

How can serial numbers be sorted using a JavaScript If Statement based on 2 criteria?

I'm currently enrolled in a JavaScript coding course where I am tackling a task involving validating serial numbers. The requirement is to check if a serial number is valid and then add it to an array to store all the valid serial numbers. The criteri ...

Modifying the input field value in React

I've been attempting to modify the value of an input field after selecting an item from the SelectField in the MaterialUI library. Despite my efforts, I have not yet succeeded. However, based on my research, everything I have written appears to be cor ...

using angularjs to dynamically apply css styles

Below is the input I have: The HTML code is shown below: <input type="number" ng-class="{negative: amount < 0}" ng-model="amount"/> This is the corresponding CSS code: .negative { color: red; } If the amount is positive, no specif ...

Finding the variance in the given situation is as simple as following these steps

To find the variance between the "Total Marks" in a question and the input texts for each answer, we need to consider specific scenarios. Firstly, if a question has only one answer, the text input should be displayed as readonly with the same value as the ...

Managing environment variables in a production server with Webpack post continuous integration can be done in a couple of ways

I am currently working on deploying a ReactJs application in production using Webpack as my build tool. To set environment variables, we are utilizing the DefinePlugin feature. new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify( ...

DxDataGrid: Implementing a comprehensive validation system for multiple edit fields

I'm currently working with a DxDataGrid within an Angular Application. Within this particular application, I have the need to input four dates. I've implemented validation rules that work well for each individual field. However, my challenge aris ...

Working with nested arrays in Mongoose/Javascript: Adding an Object to an Array within another Array

I have been attempting to add an object to an array that is nested inside another Array in Mongoose. Essentially, it's like having comments for the comments. Below is the structure of my schema: const Schema = new mongoose.Schema ({ name: {type: Str ...

Prevent pinch zoom in webkit (or electron)

Is there a way to prevent pinch zoom in an electron app? I've tried different methods, such as using event.preventDefault() on touchmove/mousemove events in JavaScript, adding meta viewport tags in HTML, adjusting -webkit-text-size-adjust in CSS, and ...

Displaying Bootstrap alert after a successful jQuery AJAX call

I have been attempting to display an alert on a form once the submission action is completed. Here is my JavaScript function: function submitForm(){ // Initialize Variables With Form Content var nomeCompleto = $("#nomeCompleto").val(); v ...

The Next.js developer encounters an issue where the build fails due to a ReferenceError on a client component, stating that "window

Just starting out with nextjs, I'm sticking to using only the basic features without diving into any advanced functionalities. During the next build process, I encountered an issue where 6 paths failed because of a ReferenceError: window is not defin ...

Two objects intersecting in space

When using AngularJS for insert and update operations, I encounter a problem where changes made to user data are reflected in the list of users. Additionally, when adding a new user, the last record's data populates all input fields. Code: User List ...

How can I incorporate eventData when using .bind() for the "keydown" event type?

I want to achieve something like this: var keydownHandler = function (ev) { alert(ev.data.test); return false; } $(document).bind('keydown', {test: 'foo'}, keydownHandler); However, the .bind method doesn't seem to be wor ...

Adding parameters to a URL is a common practice

"Adding additional information to a URL that was previously included?" I apologize for the confusing title, but I can't find a better way to phrase it. Perhaps an example will make things clearer. Let's say I have URL 1: http://example.com/?v ...

Having trouble retrieving data from a web API with complex parameters

I'm currently working with a function in the backend of my web API. Here's what it looks like: [HttpGet] public WmsWebStatus<OrdemRecebimento> CriaOrdemRecebimento(OrdemRecebimento ordemRecebimentoContrato) { try { WmsWebStatus< ...

Discover the steps to convert an image to base64 while circumventing the restrictions of the same-origin policy

I've been struggling to convert an image link to base64 in order to store it on the client-side browser (IndexedDB). Despite searching for a solution for days, I have not been able to find one that addresses my issue. While I can successfully convert ...

Unexpected behavior involving the onchange event, input validation, and the enter key

One challenge I encountered was implementing validation for a date input field in a form. The requirement was to only allow dates starting from today up to a maximum of 3 years in the future. If a valid date is entered, a modal should appear; otherwise, an ...

Internet Explorer 11 is not interested in giving attention to a disabled element

I'm trying to limit text input to only one of two fields. My approach involves checking the value of a field when it loses focus, and then disabling the other field if the initial one is not empty. Below is an example: HTML: <div class="contain ...