为什么变量是不是在控制器中可用? [英] Why variable is not available in controller?

查看:184
本文介绍了为什么变量是不是在控制器中可用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有HTML code:

I have HTML code:

<div ng-controller="ProfileLeftMenu">
<li ng-class="{'active':selectedTab == 'personal'}" ng-click="selectedTab = 'personal'" class=""><a href="1">Personal</a>
</li>
</div>

和控制器:

 $scope.selectedTab = 'first';
 if ($routeParams.page) {
   ajax.get(page, function (CbData) {
       $scope.selectedTab = page;
   });
 }

所以,如果做的:

So, if do:

{{selectedTab}} 

在HTML模板总是得到:第一

in template HTML get always: first

推荐答案

您需要用新的 $ routeParams <更新您的 $范围变量/ code>刚刚在路线改变后。对于您可以监听 $ routeChangeSuccess 事件。试试这个:

You need to update your $scope variable with the new $routeParams just after the change in route. For that you can listen for the$routeChangeSuccess event. Try this:

演示

app.js

var app = angular.module('plunker', ['ngRoute']);

app.config(['$routeProvider', function($routeProvider){

    $routeProvider
      .when('/test/:page', {

        templateUrl: function(params) {
          return 'pidat.html';
        },

        controller: 'MainCtrl'
      });

  }

]);

app.controller('MainCtrl', ['$scope', '$http', '$routeParams', function($scope, $http, $routeParams) {

  // when controller is loaded params are empty
  console.log('on controller load $routeParams', $routeParams);

  $scope.name = 'World';

  // only after you have transitioned to the new 
  // route will your $routeParams change so we
  // need to listen for $routeChangeSuccess
  $scope.$on('$routeChangeSuccess', function(){

      console.log('on $routeChangeSuccess load $routeParams', $routeParams);

    if ($routeParams.page) {
       $scope.name = $routeParams.page;
    }
  });

}]);

因此​​,对于你原来的例子,你可能会不得不做这样的事情:

So for your original example you would probably have to do something like this:

$scope.selectedTab = 'first';

$scope.$on('$routeChangeSuccess', function(){

   if ($routeParams.page) {
       ajax.get(page, function (CbData) {
           $scope.selectedTab = page;
       });
   }

});

这篇关于为什么变量是不是在控制器中可用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆