如何以angularjs方式执行以下jquery代码

时间:2014-05-09 05:43:11

标签: javascript jquery ajax angularjs checkbox

我是angularjs的新手,希望以angularjs方式执行以下操作

控制器

$scope.Filter = function($event, active, id) {
    html = "";
         if(active){
                    $http({method: 'GET', url: "someUrl.json"}).
                    success(function(data, status) {

                    html+="<p>Hey i am inside if block</p>";                    
                    });
    $("#results-display").html(html);

               }

  else{
         $http({method: 'GET', url: "someotherUrl.json"}).
                    success(function(data, status) {

                    html+="<p>Hey i am inside else block</p>";                  
});
 $("#results-display").html(html);
    }
}

基本上我使用了angularjs控制器,但是我通过将json数据附加到html来在控制器内部进行jquery方式。如何以angularjs方式显示返回的json数据?

1 个答案:

答案 0 :(得分:2)

任何 HTML操作都应该从控制器代码中省略。如果必须在代码中完成,请使用Angular Directive

但是在你的情况下,指令不是必需的。要 angularize 您的示例,您应该只设置一个范围属性(我将其命名为isActive),而是在您的标记中提供正确的HTML显示,因为范围模型是您的Javascript之间的通信控制器代码和HTML视图。

的Javascript

$scope.Filter = function($event, active, id) {
    if(active) {
        $http({
            method: 'GET',
            url: "someUrl.json"
        })
        .success(function(data, status) {
            // set $scope property
            $scope.isActive = true;
        });
    }
    else {
        $http({
            method: 'GET',
            url: "someotherUrl.json"
        })
        .success(function(data, status) {
            $scope.isActive = false;
        });
    }
};

这段代码很容易缩短,但仍可以做同样的事情。

$scope.Filter = function($event, active, id) {
    $http({
        method: "GET",
        url: active ? "someUrl.json" : "someotherUrl.json"
    })
    .success(angular.bind(active, function(data, status) {
        $scope.isActive = this;
    }));
};

HTML

<div id="results-display" ng-switch="isActive">
    <p ng-switch-when="true">Hey i am inside if block</p>
    <p ng-switch-when="false">Hey i am inside else block</p>
</div>

如果您未在代码中的任何位置使用此div,则可以完全省略其ID属性,因为角度属性将相应地起作用。

更复杂的操作

如果此示例是更复杂的实际代码的简化版本(如果它不仅仅是活动与否),您还可以在控制器中设置文本值,然后在HTML中绑定它。只要值是严格的原语并且不涉及HTML,这样做就没有错。任何其他范围属性也只是对象/基元的基元或对象。他们只是数据

...
$scope.activityText = "Hey i am inside if block";
...

然后在HTML中只需绑定到此范围属性

<div id="results-display">
    <p ng-bind="activityText"></p>
</div>

这意味着每当您更改$scope.activityText值(无论是.Filter函数还是其他任何地方),它都会相应地反映在您的HTML中。

您还可以使用{{}}使用其他符号,但我更喜欢ng-bind属性,因为它不要求您将ng-cloak放在元素{{3}上在Angular开始之前。