简体   繁体   中英

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.

Here the scope are variables defined in the function getCurrentTab which will be initialized only on the function call.

But if I define these variables outside the function these gets initialized multiple times .

So is there a way to define the scope variables only once which will be modified by getCurrentTab function only.

Thanks in advance!

If you're familiar with the $routeProvider service, here's an easy way to accomplish the same task.

JS

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

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

}]);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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