2014-11-03 126 views
0

你好,我想知道重置angularjs的scoep,這裏是例子:如何重置範圍變量Angularjs

HTML:

<div ng-show="showSearchBlock">Search Block</div> 

的Javascript:

app.controller('MainController', function($rootScope) { 
    $rootScope.showSearchBlock = false; 
}); 

app.controller('ProfileController', function($scope) { 
    $scope.showSearchBlock = true; 
}); 

app.controller('AboutUsController', function($scope) { 

}); 

如果我路由到About us頁面,$scpoe.showSearchBlock將爲false(來自MainController)。

但是,如果我路由到Profile$scope.showSearchBlock將是真實的,然後我路由到About Us它將仍然如此。我想$scope.showSearchBlock將只在ProfileController真實,我應該怎麼做?

而且我不想在每個控制器中重置這個變量,我想由控制器自動完成。

非常感謝。

+0

'AboutUsController'嵌套在'ProfileController'下嗎? – 2014-11-03 11:21:39

+0

是的,AboutUsContrller在ProfileController下。 – 2014-11-03 11:44:52

+0

嘗試在您更改路線的配置部分。 – Jai 2014-11-03 11:51:31

回答

0

添加事件偵聽器的根範圍,然後做你想做的

$rootScope.$on('$routeChangeStart', function(next, current) { ... check your url if you want to show the search box in that url make $rootScope.showSearchBlock = true else make it false. and remove other instances of the $rootScope.showSearchBlock put this on your main controller ... });

+0

非常感謝。這是正確的。 – 2014-11-03 12:00:58

+0

@MatanYedayev很高興看到你有答案。繼續工作 – madu 2014-11-05 03:33:47

0

你必須使用服務來共享數據:從每個控制器

app.factory('shareDataService', function() { 

var formData = {}; 

    return { 
     getData: function() { 
      //You could also return specific attribute of the form data instead 
      //of the entire data 
      return formData; 
     }, 
     setData: function (newFormData) { 
      //You could also set specific attribute of the form data instead 
      formData = newFormData 
     }, 
     resetData: function() { 
      //To be called when the data stored needs to be discarded 
      formData = {}; 
     } 
    }; 
}); 

進樣和要求這裏。