范围未更新AngularJS

时间:2013-01-24 15:53:54

标签: javascript angularjs

我很难过......我煮斧头的粥。 如果可以的话,请帮助我处理我的问题。 我的html代码中有这个结构(ng-controller在换行标签上):

<a ng-repeat="subitem in cur_submenu" ng-href="#/{{subitem.href}}/">{{subitem.name}}</a>

在JS中我有: 1)RouteProvider

$routeProvider.
      when('/:lvl1', {
          template:'<div ng-include="htmlUrl">Loading...</div>',
          controller: 'MainCtrl'
      })

2)控制器

function MainCtrl($scope, $http, $routeParams){
  var lvl = window.location.hash.split('/');
  if ($scope.submenu) {
    //if data was fetch earlier, then set currentMenu
    $scope.cur_submenu = $scope.submenu[lvl[1]];
  } else {
    MainCtrl.prototype.fetchData();
  }

  MainCtrl.prototype = {
    fetchData: function(){
      /*
      * Get data about navigation
      */
      $http({method: 'GET', url: 'data/main.json'}).
      success(function(data){
        $scope.menu = data.menu;
        $scope.submenu = data.submenu;
        $scope.cur_submenu = data.submenu[lvl[1]] //current submenu for my location
      });
   }
}

但是当我在网站上更改我的位置(hash-nav)时,我的页面上没有更新...请帮助我。我的网站的完整版:http://amiu.ru

1 个答案:

答案 0 :(得分:1)

您无需通过原型设计向Controller添加功能。在视图中调用的函数将在$ scope上声明,如下所示:

function MainCtrl($scope, $http, $routeParams){
  var lvl = window.location.hash.split('/');
  if ($scope.submenu) {
    //if data was fetch earlier, then set currentMenu
    $scope.cur_submenu = $scope.submenu[lvl[1]];
  } else {
    $scope.fetchData();
  }

  $scope.fetchData = function(){
      /*
      * Get data about navigation
      */
      $http({method: 'GET', url: 'data/main.json'}).
          success(function(data){
            $scope.menu = data.menu;
            $scope.submenu = data.submenu;
            $scope.cur_submenu = data.submenu[lvl[1]] //current submenu for my location
          });
   };
}

在所有其他情况下,如果您在$ scope函数之外的$ scope上执行更改,则需要手动调用$scope.$apply()对摘要进行排队并更新您的视图。