使用AngularJS操作DOM

时间:2014-08-18 13:25:30

标签: javascript angularjs dom

我试图用angularjs使用指令操作我的表。

我想在id = 2的第一个td中添加一个新类,如下所示:

gameApp.directive('mapActivity', function() {
    return {
        link: function(scope, element, attrs) {
            angular.element('.click#1').addClass('dotted');
        }
    };
});

我试图"使用" drictive在这里:

<map-activity>
<table ng-bind-html="safeHtml()">
</table>
</map-activity>

但没有任何反应。第一个TD没有得到这个类&#39;点缀&#39;。我做错了什么?

这是我的控制器:

var gameApp = angular.module("gameApp", ['ngRoute','ngSanitize']);

gameApp.service('link', function() {
    this.user = false;
});
gameApp.filter('unsafe', function($sce) {
    return function(val) {
        return $sce.trustAsHtml(val);
    };
});

gameApp.directive('mapActivity', function() {
    return {
        priority: 1,
        restrict: 'A',
        link: function(scope, element, attrs) {
            angular.element('.click#1').addClass('dotted');
        }
    };
});
function makeTableFrom(str) {
    var k = 1;
    result = "";

    for(var i = 1; i <= 8; i++) {
        result += '<tr>';

        for(var j = 1; j <= 20; j++) {
            if(str[k] == '#') {
                result += '<td id=' + k + '">#</td>';
            }
            else if(str[k] == '&') {
                result += '<td class="click" val="water" id="' + k + '">&</td>';
            }
            else {
                result += '<td class="click" id="' + k + '"><a href="#"></a></td>';
            }

            k++;
        }
        result += '</tr>';
    }
    return result;
}


gameApp.config(function($routeProvider) {
    $routeProvider

    .when('/', {
            templateUrl : 'partials/firstpage.html',
            controller  : 'firstPageCtrl'
    })

    .when('/game', {
            templateUrl : 'partials/game.html',
            controller  : 'gameCtrl'
    });

});

gameApp.controller("firstPageCtrl", function($scope,$http,link,$location) {
    $scope.doLogin = function() {
        $http.post("lib/action.php", {username: $scope.username, password: $scope.password}).success(function(data) {
            if(data) {
                link.user = data;
                console.log(link.user);
                $location.path("/game");
            }
        }).error(function(data) {
            console.log(data);
        });
    };
});


gameApp.controller("gameCtrl", function($scope,$http,link,$location,$sce) {
    //$scope.trr = [1,2,3,4,5,6,7,8];
    //$scope.tdd = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20];
    $scope.getMonsters = "1";
    var map;

    $http.post("lib/action.php", {monsters: $scope.getMonsters}).success(function(data) {
        map = data;
        console.log(map);
        $scope.result = makeTableFrom(data);
        console.log($scope.result);
    });

    $scope.safeHtml = function() {
        return $sce.trustAsHtml($scope.result);
    };
    if(link.user) {
        /*$scope.message = "fisk";
        console.log(link.user);*/
    } else {
        /*$scope.message = "Ledsen fisk";
        console.log("Är inte satt");*/
    }

});

正如您所看到的,我使用javascript函数来为HTML添加变量,然后在我的视图中使用它,将其传递给过滤器。

当我按Ctrl + u查看页面来源时,我无法看到正在打印的td和tr。这会影响它无法正常工作的原因吗?

3 个答案:

答案 0 :(得分:1)

尝试分配不同的prioritymap-activity指令,因此会在ng-bind-html之后处理

正如@Abhishek Jain和@Dalorzo所指出的那样,你的指令必须属性应用于同一个DOM元素

.directive('mapActivity', function() {
    return {
       priority: 0,   // check what priority ng-bind-html have and set it to be more than that.
       link: function(scope, element, attrs) {
          ...
       }
    }
})
  

<强>优先

     

当在单个DOM元素上定义了多个指令时,   有时需要指定指令的顺序   适用。优先级用于在指令之前对指令进行排序   编译函数被调用。优先级定义为数字。   首先编译具有更高数字优先级的指令。   预链接功能也按优先级顺序运行,但后链接   函数以相反的顺序运行。指令的顺序与   相同的优先级未定义。默认优先级为0。

答案 1 :(得分:1)

您需要将指令添加到要将其附加到的标记。在您的指令声明中,您已将myDirective声明为属性指令,但您在html中将其用作元素指令。

假设.click#1选择器对应于第一个td,并且您希望指令成为属性,则需要执行以下操作: -

<table ng-bind-html="safeHtml()" map-activity>

编辑: -

如果你想要定位每一行的第一个td,你可以像这样定义你的指令: -

app.directive('mapActivity', [function(){
   return {
        restrict: 'A',
        link: function($scope, iElm, iAttrs, controller) {
            iElm.find('tr td:first-of-type').addClass('dotted');
        }
    };
}]);

答案 2 :(得分:0)

你正在做的事情有点奇怪,因为你正在做的是创建一个新元素,而不是用一个属性修改你当前的表元素,如:

<table ng-bind-html="safeHtml()" map-Activity="">
</table>

然后:

gameApp.directive('mapActivity', function() {
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
           scope.$watch(attr.ngBindHtml, function(value) {
              angular.element('.click#1').addClass('dotted');                              
           });
        }
    };
});

此外,请确保指定使用限制属性的指令类型A =属性,E =元素,C =类,......可以合并restrict: 'EAC', < / p>

您的示例版本中的link函数将首先执行,另外一些浏览器将难以理解它的未知元素,因为这样可能更好地在表级移动您的指令。