【发布时间】:2014-08-18 13:25:30
【问题描述】:
我正在尝试使用指令使用 angularjs 来操作我的表格。
我想向第一个 id=2 的 td 添加一个新类,如下所示:
gameApp.directive('mapActivity', function() {
return {
link: function(scope, element, attrs) {
angular.element('.click#1').addClass('dotted');
}
};
});
我试图在这里“使用”驱动:
<map-activity>
<table ng-bind-html="safeHtml()">
</table>
</map-activity>
但是什么也没发生。第一个 TD 没有得到“dotted”类。我做错了什么?
这是我的控制器:
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。这会影响它为什么不工作吗?
【问题讨论】:
-
请用你的代码创建 jsfiddle。
-
你确定你的指令码是在表格内容填完后触发的吗?也许您尝试将类添加到不存在的元素,然后填充表格。可能将
$timeout与 0 添加到您的指令中,因此它首先获取内容。
标签: javascript angularjs dom