Switching Angular view not updating variables

437 Views Asked by At

I'm just building out a simple app to learn AngularJS and having trouble updating variables when switching views. Here's what I have so far:

function routeConfig($stateProvider, $urlRouterProvider) {
$stateProvider
  .state('home', {
    url: '/',
    templateUrl: 'app/main/main.html',
    controller: 'MainController',
    controllerAs: 'main'
  })

  .state('team', {
    url: '/team',
    templateUrl: 'app/main/team.html',
    controller: 'MainController',
    controllerAs: 'main'
  })
$urlRouterProvider.otherwise('/');
}

Here's part of my controller:

function MainController($timeout, webDevTec, toastr, $resource, $scope) {
var vm = this;

var GetTeam = $resource('https://apisite.com/api_endpoint/:teamId', {teamId: '@id'});
vm.teamName = '';
function getTeamInfo(id) {
  var teamObj = GetTeam.get({teamId: id});
    $timeout(function(){
      vm.teamName = teamObj["name"];
    },100)        
};

vm.getTeamInfo = getTeamInfo;
}

Then in my main.html I call getTeamInfo with a ng-click:

 <ul class="list-group">
<li class="list-group-item" ng-repeat="team in main.teams" ng-click="main.getTeamInfo(team.id)"><a href="#/team">{{ team.name }}</a></li>
 </ul>

Clicking on that link will take you to team.html:

<div class="row">
            <div class="col-sm-12">
                <h3>{{ main.teamName }}</h3>
                <ul class="list-group">
                  . . . 
                </ul>
            </div>
        </div>

For some reason "main.teamName" is not updating. I've tried the $scope.$apply(function(){vm.teamName = teamObj["name"]} approach as well with no luck. I also did 'console.log(teamObj["name"])' before vm.teamName and 'console.log(vm.teamName)' after to see if I get the expected results and I do. I just have no idea now why it's not updating the new view.

Thank you for your insight, patience, and time!

UPDATE 1

I also tried using $scope on my variables ($scope.teamName) and using $scope.$apply(function(){$scope.teamName = teamObj["name"]}) with no luck.

UPDATE 2

I also tried called $scope.$apply(); after 'vm.teamName = teamObj["name"]' with no luck

1

There are 1 best solutions below

0
Matt Herbstritt On

It looks like teamObj is not populated yet at the point when you assign vm.teamName

You would make your life so much easier if you just reference teamObj rather than creating a new property.

I made a plunker based on a modified version of your code to show a possible implementation. I couldn't get it to work using the controllerAs syntax and I'm not entirely sure why (possibly because of some issues related to sharing a controller; not sure). Anyway, hopefully it will be of some help to you.

DEMO

app.js

var app = angular.module('plunker', ['ui.router', 'ngResource']);

app.controller('MainController', MainController);
app.config(routeConfig);

function MainController($timeout, $scope, $resource) {

  // mock data
  var GetTeam = $resource('http://demo7592070.mockable.io/teams/:teamId', {teamId: '@id'});
  //var GetTeam = $resource('https://apisite.com/api_endpoint/:teamId', {teamId: '@id'});

  $scope.teamName    = 'undefined';
  $scope.getTeamInfo = getTeamInfo;

  function getTeamInfo(id) {

    var teamObj = GetTeam.get({teamId: id});

    $scope.teamName = teamObj.name;
    $scope.teamObj = teamObj;

  };

}

function routeConfig($stateProvider, $urlRouterProvider) {

$stateProvider
  .state('home', {
    url: '/',
    templateUrl: 'main.html',
    controller: 'MainController'
  })

  .state('team', {
    url: '/team',
    templateUrl: 'team.html',
    controller: 'MainController'
  });

  console.log('ROUTECONFIG');

  $urlRouterProvider.otherwise('/');

}

index.html

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

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />

       <!-- JS (load angular, ui-router, and our custom js file) -->
    <script src="http://code.angularjs.org/1.2.13/angular.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.8/angular-ui-router.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.2/angular-resource.js"></script>
    <script src="app.js"></script>

  </head>

  <body>
    <a ui-sref="home">home</a>
    <a ui-sref="team">team</a>
    <div ui-view=""></div>
  </body>

</html>

main.html

<h1>Home</h1>

<pre>$scope.teamName        => {{teamName}}</pre>
<pre>$scope.teamObj         => {{teamObj}}</pre>
<pre>$scope.teamObj.name    => {{teamObj.name}}</pre>

<button ng-click="getTeamInfo(1)">Get Team 1</button>

team.html

<h1>Team</h1>

<pre>$scope.teamName        => {{teamName}}</pre>
<pre>$scope.teamObj         => {{teamObj}}</pre>
<pre>$scope.teamObj.name    => {{teamObj.name}}</pre>

<button ng-click="getTeamInfo(2)">Get Team 2</button>