簡體   English   中英

如何在$ Angular中使用$ http服務添加部分頁面功能?

[英]how to add partial page functionality using $http service in angular?

我想使用angular中的$ http服務成功加載部分頁面后執行操作。

該操作是根據范圍值選中該復選框。

請任何人幫助我。

源代碼在這里:這是實際的代碼。

$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");
    });

成功后,以下代碼將無法正常工作。

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

我將此代碼放在成功函數中。 請建議我需要在哪里放置此代碼。

嗨,您的比較可能很糟糕。

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

我不知道$ scope.selected中的值是什么,但是我認為該值是一個復選框狀態,為布爾型。 因此,您正在將布爾值與字符串進行比較。

查看https://docs.angularjs.org/api/ng/function/angular.equals

Angularjs簡短介紹:

通常,您應該盡量減少在angularjs中使用jQuery,因為這兩個概念相互沖突。 Angularjs基於作用域變量和模板表達式之間的綁定。 因此,對於復選框,您可以輕松地在沒有jQuery的情況下進行處理,如下所示:

您可以在這里找到一個很好的解釋: https : //stackoverflow.com/a/14520103/4852206

您在這里看到的是您i.ex。 可以將復選框輸入綁定到數組。 如果要更改數組內容,則復選框會在偵聽並確實在運行中更改狀態(選中或未選中),而無需檢查它是否處於活動狀態,也不需要Jquery dom操作。

我寫了上面的摘錄,因為如果您將自己的方法用作最佳實踐,則會遇到大量的非結構化和難以閱讀的代碼。 另外,恐怕您正在控制器函數中使用代碼。 在Angularjs中,控制器不是用於dom操縱的,您應該僅將其用於設置/更改范圍變量,或者僅使用最小的業務邏輯(通常在這里避免使用!)業務邏輯應進入服務,而dom操縱應進入指令。

你的問題:

請提供有關您的問題/邏輯的更多信息。 請提供示例復選框,以及您通過$ http從服務器提取的示例信息。請同時提供您要實現的目標。 然后,我們可以為您提供清晰的答案。

抱歉,我知道這是沒有答案,但是由於我在這里還很陌生,因此我無法添加評論。

編輯好的,感謝您對@Likeee的評論,我想我明白了。 您的頁面上有一組復選框。 在頁面加載時,您要檢查哪個復選框需要處於活動狀態。 頁面加載中哪個復選框處於活動狀態的邏輯來自服務器端,對嗎? 如果是的話,我將按照以下角度結構進行處理(我創建了一個小提琴以更好地理解: https : //jsfiddle.net/pfk9u3h0/4/

首先,您需要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>

這段HTML片段做了幾件事:

首先,它聲明要使用哪個控制器(此處為“ AppController”。其次,它創建一個帶有復選框的標簽。該標簽具有Angularjs指令ngRepeat並導致顯示與AppController中數組“ productFilter”所包含的復選框一樣多的復選框。

JavaScript包含與HTML和服務對話的控制器。 該服務也在下面聲明。

控制器:

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);
    }
    };    
});

使用$scope.productFilter = ['Red pants', 'Green Pants', 'Yellow pants', 'Blue pants']; 我們聲明一個數組,在HTML中對其進行迭代。 這包含所有帶有名稱的復選框。

現在我們需要一個帶有所有選中復選框的數組。 這保存在$ scope.selection中,並綁定到我最后顯示的服務:

$scope.selection = SelectionService.selection; 

如果您取消選中或選中復選框,則控制器內的其余部分僅用於設置新值。

服務:

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;
});

該服務正在執行4件事:它保存並初始化(如果您願意)數組“選擇”。 它提供了一種從服務器加載新數據並將其保存到陣列的方法。 在這里重要的是使用復制方法,否則將丟失所有綁定。 它提供了設置和刪除選擇的方法。 在我的示例中,我不使用load方法,因為這里沒有任何服務器端腳本...我只是采用初始化值。 但是您應該使用我的加載方法。

終於我達到了我的要求:

 // $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);
          } 
      }; 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM