【问题标题】:how to add partial page functionality using $http service in angular?如何在 Angular 中使用 $http 服务添加部分页面功能?
【发布时间】:2015-07-13 14:29:12
【问题描述】:

我想在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');
          }

我将此代码放在成功函数中。 请告知我需要在哪里放置此代码。

【问题讨论】:

  • 你不能只使用像 ng-include 这样的东西来实现所需的功能吗?您的代码看起来非常“无棱角”。
  • 请指教如何实现?

标签: javascript jquery angularjs angularjs-scope


【解决方案1】:

一个简短的 Angularjs 附记:

一般来说,你应该尽可能减少在 angularjs 中使用 jQuery,因为这两个概念是相互矛盾的。 Angularjs 基于作用域变量和模板表达式之间的绑定。因此,对于一个复选框,您可以在没有 jQuery 的情况下轻松处理它,如下所示:

你可以在这里找到一个很好的解释: https://stackoverflow.com/a/14520103/4852206

你在这里看到的是,你 i.ex。可以将复选框输入绑定到数组。如果您正在更改数组内容,则复选框正在侦听并且会即时更改状态(选中或未选中),而无需检查它是否处于活动状态并且不需要 Jquery dom 操作。

我写了上面的附言,因为如果你将自己的方式作为最佳实践,你会遇到大量的非结构化和不可读的代码。另外,我担心您正在控制器功能中使用您的代码。在 Angularjs 中,控制器不用于 dom 操作,您应该只使用它来设置/更改范围变量或只是一个最小的业务逻辑(通常在这里避免它!)业务逻辑应该进入服务,dom 操作应该进入指令。

您的问题:

请为您的问题/逻辑提供更多信息。请提供示例复选框,以及您通过 $http 从服务器中提取的示例信息 请同时提供您想要达到的目标。然后我们可以帮助您给出明确的答案。

抱歉,我知道这不是答案,但实际上我无法添加 cmets,因为我在这里很新。

编辑 好的,感谢您对@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 方法,因为我这里没有任何服务器端脚本……我只取初始化值。但是你应该使用我的加载方法。

【讨论】:

  • 谢谢..GobiRan。最后我达到了我的要求。
     // $scope.getCustomObjectsBasedOnObjectTypeSelection = getCustomObjectsBasedOnObjectTypeSelection; $scope.selected = ['显示全部']; var IsActive = ""; $scope.objectSelection = function objectSelection(objectType) { var idx = $scope.selected.indexOf(objectType); // 当前被选中 if (idx > -1) { $scope.selected.splice(idx, 1); } // 新选择 else { $scope.selected.push(objectType); } }; 
【解决方案2】:

您好,您的比较可能很糟糕。

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

我不知道 $scope.selected 中的值是什么,但我认为这个值是一个布尔类型的复选框状态。因此,您正在将布尔值与字符串进行比较。

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

【讨论】:

  • $scope.selected 包含值数组。出于测试目的,我只在该数组中传递一个值。即使我也会为 eg..if(angular.equals("ShowActivatedObjects", "ShowActivatedObjects")) 传递直接值。这也行不通。请指教。
【解决方案3】:

终于达到了我的要求:

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

【讨论】:

    猜你喜欢
    • 2015-08-05
    • 2022-01-13
    • 2011-04-25
    • 1970-01-01
    • 1970-01-01
    • 2020-03-12
    • 2019-08-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多