0

I want to perform operation after successfully loaded the partial page using $http service in angular.

The operation is to check the checkbox based on the scope value.

Please anyone help me.

Source Code here: This is actual code.

$http({
        url : './resources/staticPages/custom-object-filter.html',
        method : "GET"
    }).success(function(data, status) {         
            $scope.data = data;             
            jQuery("objectViewPartial").html($compile($scope.data)($scope));
            //console.log($scope.selected);
          if(angular.equals($scope.selected, "ShowActivatedObjects")) {
                 $("#ShowActivatedObjects").attr('checked','true');
          } else {
                $("#ShowActivatedObjects").attr('checked','false');
          }                 

    }).error(function(data, status) {
            console.log("some error occured partial page");
    });

After getting success the below code is not working.

if(angular.equals($scope.selected, "ShowActivatedObjects")) {
                 $("#ShowActivatedObjects").attr('checked','true');
          } else {
                $("#ShowActivatedObjects").attr('checked','false');
          }

I placed this code inside of success function. Please advice where i need to place this code.

bagya
  • 51
  • 10

3 Answers3

0

Hi your comparison is probably bad.

if(angular.equals($scope.selected, "ShowActivatedObjects")) {

I don't know what value is in $scope.selected, but i think this value is a checkbox state which is boolean type. So you are comparing boolean with string.

Check out https://docs.angularjs.org/api/ng/function/angular.equals

Likeee
  • 11
  • 2
  • $scope.selected contains array of values. For testing purpose i am passing only one value in that array. Even though if i wil pass direct value also for eg..if(angular.equals("ShowActivatedObjects", "ShowActivatedObjects")) . This also not working. please advice. – bagya Jul 14 '15 at 09:40
0

A short Angularjs excursus:

In general you should minimize the use of jQuery within angularjs as far as you can, because both concepts are working against each other. Angularjs is based on bindings between scope variables and the template expressions. So for a check box you can easy handle it without jQuery as follows:

A good explanation you can find here: https://stackoverflow.com/a/14520103/4852206

What you are seeing here is, that you i.ex. can bind the checkbox inputs to an array. If you are changing the array content, the checkboxes are listening and do change there state (checked or unchecked) just on the fly without the need of checking if it is active and without the Jquery dom manipulation needs.

I wrote the above excursus, because you will run into huge unstructured and unreadable code if you will use your way as best practice. Also I am afraid, that you are using your code within your controller function. In Angularjs the controller is NOT for dom manipulation, you should only use it for setting / changing the scope variables or just a minimal business logic (in general avoid it here!) Business logic should go into services and dom manipulation should go into directive's.

Your question:

Please provide more information for your problem / logic. Please provide sample checkboxes, and sample information that you pull from the server via $http Please provide also what you want to achieve exactly. Then we can help you with a clear answer.

Sorry I know this is no answer, but I cannot add comments actually cause I am quite new here.

EDIT Ok thanks to your comment to @Likeee I think I got you. You have a set of checkboxes on your page. On page load you want to check which checkbox needs to be active. The logic which checkbox is active on pageload comes from the server side, is that correct? If yes I would handle it as follows with angular structure (I created a fiddle for a better understanding: https://jsfiddle.net/pfk9u3h0/4/)

First you need your HTML:

<body ng-app="myApp" ng-controller="AppController">
    <label ng-repeat="filter in productFilter">
        <!--
            simply checking if the array contains the entry. if not, it is not selected. On a click event, the selected     item is added to the array.
          -->  
        <input
        type="checkbox" 
        value="{{filter}}" 
        ng-checked="selection.indexOf(filter) > -1"
        ng-click="toggleSelection(filter)"/> {{filter}}
    </label>
    "selection Array within SelectionService": <br />{{selection}} <br /><br />
    as you see, the array is also updating when you check or uncheck a box
</body>

This HTML snipped does several things:

First it declares which controller (here "AppController" to use. Second it creates a label with a checkbox inside. The label has the Angularjs directive ngRepeat and causes to show as much checkboxes as the array "productFilter" within AppController contains.

The Javascript contains a controller which is talking to your HTML and to a service. The service is also declared below.

Controller:

app.controller("AppController", function( $scope, SelectionService ) {
    // available filter checkboxes
    $scope.productFilter = ['Red pants', 'Green Pants', 'Yellow pants', 'Blue pants'];

    // selected filter
    // normally you just would have this: $scope.selection = ['Red pants', 'Blue pants'];
    // But now you want to pull the selection elsewhere:
    // The selection should go in a service, because it can happen, that other pageviews of your page shall 
    // change the values or even get the selection as well.
    $scope.selection = SelectionService.selection; // Bind the selection to the service
    // With the proper binding, you can change the selection within other modules / pages etc. and this
    // checkbox fields will update based on the service data!


    //I just initialize the service selection array, butbut you really want to pull it from server like this:
   // SelectionService.loadSelection() 
//      .then(function(data) {
            // if you like, yo can do sth. with this promise callback
    //  });

    // Change selection for the clicked input field
    $scope.toggleSelection = function toggleSelection(filter) {
        var idx = $scope.selection.indexOf(filter);

        // is currently selected
    if (idx > -1) {
        SelectionService.removeSelection(idx);
    }

    // is newly selected
    else {
        SelectionService.addSelection(filter);
    }
    };    
});

With $scope.productFilter = ['Red pants', 'Green Pants', 'Yellow pants', 'Blue pants']; we declare an array over which we iterate within our HTML. This contains all checkboxes with names.

Now we need an array with all selected checkboxes. This is saved in $scope.selection and is bound to the service which i show at the end:

$scope.selection = SelectionService.selection; 

The rest within the controller is just to set the new values, if you uncheck or check a checkbox

The Service:

app.service("SelectionService", function ($http, $q) {
    var obj = {
        selection : ['Red pants', 'Blue pants'], 
        loadSelection : function(){ 
            var that = this;
            var deferred = $q.defer();
            var config = {
                responseType : "json",
                cache: true
            }   
            $http.get("/getSelectionFromServer", null, config)
                .success(function(response){
                    if(response) {
                        // IMPORTANT: Use a deep copy, otherwise you will loose the binding
                        angular.copy(response,that.selection);
                    }
                    deferred.resolve(response);
                })
                .error(function(){
                  deferred.reject();
               });
            return deferred.promise;
        },
   addSelection : function (filter) {
        this.selection.push(filter)
    },
    removeSelection : function (index) {
        this.selection.splice(index, 1);
    };

    return obj;
});

The Service is doing 4 things: It holds and initilizes (if you like) an array "selection". And it offers a method to load new data from server and save it to the array. Here it is important that you use the copy method, otherwise you will loose any binding. And it offers methods to set and remove selections. in my example i dont use the load method, because I do not have any serverside scripts here...I just take the initialization values. But you should use my load method.

Community
  • 1
  • 1
GobiRan
  • 154
  • 1
  • 8
  • Thanks..GobiRan. Finally i achieve my requirement.
     
      // $scope.getCustomObjectsBasedOnObjectTypeSelection = getCustomObjectsBasedOnObjectTypeSelection;
        $scope.selected = ['Show All'];
        var IsActive = "";      
       $scope.objectSelection = function objectSelection(objectType) {
          var idx = $scope.selected.indexOf(objectType);
         
           // is currently selected
           if (idx > -1) { 
             $scope.selected.splice(idx, 1);
           }        
           // is newly selected
           else {
              $scope.selected.push(objectType);
           } 
       }; 
    – bagya Jul 14 '15 at 10:45
0

Finally i achieved my requirement:

 // $scope.getCustomObjectsBasedOnObjectTypeSelection = getCustomObjectsBasedOnObjectTypeSelection;
       $scope.selected = ['Show All'];
       var IsActive = "";            
      $scope.objectSelection = function objectSelection(objectType) {
         var idx = $scope.selected.indexOf(objectType);

          // is currently selected
          if (idx > -1) {   
            $scope.selected.splice(idx, 1);
          }           
          // is newly selected
          else {
             $scope.selected.push(objectType);
          } 
      }; 
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
bagya
  • 51
  • 10