简体   繁体   中英

AngularJS: Update view content from layout

You can see what I am trying to do in the following image.

在此处输入图片说明

Mainly I have two sections on the page. The Header section contains a common menu and a search textbox.

When the user clicks on the menu, for instance Movies, the Movies.html view will be loaded in the section marked with ng-view.

Each view has his own controller defined as following:

$routeProvider
    .when("/", { templateUrl: "app/albums.html", controller: "albumController" })
    .when("/games", { templateUrl: "app/games.html", controller: "gamesController" })...etc

So far so good. The idea is that when the user searches something on the textbox the current view will be updated.

I could have a commonController wrapping the searchTextbox HTML but...how can I update the $scope of the current loaded view from this controller?

What is the best approach to achieve that?

Thanks all of you

I think you should use service for that.

Your commonController will notify this service:

commonController.$inject = ['NotifyViewFactory'];
function commonController(NotifyViewFactory){
  var vm = this;
  vm.inputModel = '';

  this.notifyService = function(){
    NotifyViewFactory.setValue(vm.inputModel); 
  };

  //may be in your example better to listen when route changed:
  //and then use service
  $scope.$on('$routeChangeSuccess', function(scope, next, current){
    NotifyViewFactory.setValue(vm.inputModel);
  });
}

And factory will look like this:

NotifyViewFactory.$inject = ['$rootScope'];
function NotifyViewFactory($rootScope){
  return {
    setValue: setValue
  };

  function setValue(data){
    //do something with data if necessary
    $rootScope.$emit('inputUpdated', data);
  }
}

And view controller:

viewController.$inject = ['$rootScope', '$scope'];
function viewController($rootScope, $scope){
  $rootScope.$on('inputUpdated',function(event, data){
    $scope.someValue = data.someValue;
  });
}

So, that data from commonController can be passed to viewController without any changes, or if you need some change - you can do that in setValue method of NotifyViewFactory (before $rootScope.$emit call).

The easiest solution is to use a $scope variable that is accessible across controllers.

In your header controller define:

'$scope.global = {};'

Then assign the search value to that object, such as:

'$scope.global.searchValue = "Ready Player One"'

You'll then be ale to access that variable in your other controllers without having to go through all the complexity of using a service.

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