R
R
rakro2015-10-25 20:12:37
Angular
rakro, 2015-10-25 20:12:37

Creating a module in angular?

There is a task to make sure that the parameters for the filter in ng-repeat are in the url (as with a GET request). And with feedback. The filter has changed, the url has changed, and vice versa. I achieved this in the following way. There is a search object that is passed to the filter and initialized as follows:

var searchObj = $location.search();
    
    $scope.search = {
      name   : searchObj.name  || "",
      group  : searchObj.group || "0",
      type   : searchObj.type  || "employee",
    };

There is a watcher for this object and a function that changes the url:
$scope.$watch('search', function() {
      $scope.updateUrl();
    },true);

    $scope.updateUrl = function(){
      $scope.search.name          ? $location.search("name",$scope.search.name )  : $location.search("name", null);
      $scope.search.group !== "0" ? $location.search("group",$scope.search.group) : $location.search("group",null);
      $scope.search.type          ? $location.search("type",$scope.search.type)   : $location.search("type",null);
    }

and the same for feedback:
$rootScope.$on('$locationChangeSuccess', function () {
      $scope.updateSearch();
    });

    $scope.updateSearch = function(){
      var searchObj = $location.search()
      if (searchObj.type)  {$scope.search.type   = searchObj.type};
      if (searchObj.name)  {$scope.search.name   = searchObj.name};
      if (searchObj.group) {$scope.search.group  = searchObj.group};
    }

I would like to put all this clumsy functionality into a module so that you can connect it on different pages (the backend is responsible for routing, each page is a separate angular application) in different controllers, with different objects for searching. Need ideas from the angular guru how to do it all and not be ashamed later?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nicholas, 2015-10-26
@healqq

It would be best to make a service that contains the current search value, has a setter and getter, as well as a subscription to locationChange, and when changing the value (both through the setter and when changing the url), a broadcast is called. We already listen to this broadcast in the controller and do what we want. That is, the scheme is as follows: controller / location -> {search value change} -> service -> {search value changed} -> everyone who is subscribed.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question