简体   繁体   English

如何在angularJS中初始化控制器$ scope变量

[英]How to initialize the controller $scope variables in angularJS

I have one view where I am accessing scope variables from on angular controller function. 我有一个视图,可以从角度控制器功能访问范围变量。

$scope.getCurrentTab = function (tab) {
 $scope.yourReportEnabled = (tab === 'REPORTS');
 $scope.currentTab = tab;
}

in the view I have two anchors on click of which I call getCurrentTab() by passing the tab name as a parameter. 在视图中,单击时有两个锚点,我通过将选项卡名称作为参数传递来调用getCurrentTab()

Here the scope are variables defined in the function getCurrentTab which will be initialized only on the function call. 范围是在函数getCurrentTab中定义的变量,这些变量仅在函数调用时初始化。

But if I define these variables outside the function these gets initialized multiple times . 但是,如果我在函数之外定义这些变量,则会gets initialized multiple times它们。

So is there a way to define the scope variables only once which will be modified by getCurrentTab function only. 因此,有一种方法只能定义variables only once范围variables only once该范围variables only oncegetCurrentTab函数修改。

Thanks in advance! 提前致谢!

If you're familiar with the $routeProvider service, here's an easy way to accomplish the same task. 如果您熟悉$routeProvider服务,这是一种完成同一任务的简单方法。

JS JS

angular.module('ForeverLeather').config(['$routeProvider', function($routeProvider) {
  $routeProvider

  .when('/home', {
    templateUrl: 'js/views/home/index.html',
    activetab: 'home'
  })

}]);

HTML 的HTML

      <li class="nav-home">
        <a id="home-btn" href="#/home" name="home-btn" ng-class="{active: $route.current.activetab == 'home'}">Home</a>
      </li>

using ng-class to determine which tab is active 使用ng-class确定哪个选项卡处于活动状态

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM