我正在尝试使用angular元素创建元素并附加到某个元素。新元素有一个ng-if告诉它是否需要根据范围变量条件可见。但由于某种原因,它没有对变化作出反应。这是代码:
return {
restrict: 'A',
scope: {
object: '=on'
},
compile: function(elem) {
var td = angular.element('<td></td>' ),
closeRow = angular.element('<i class="fa fa-arrow-circle-right" ng-if="!object.open"></i>' ),
openRow = angular.element('<i class="fa fa-arrow-circle-down" ng-if="object.open"></i>');
td.append(closeRow ).append(openRow);
elem.append(td);
return link;
}
}
function link($scope, elem) {
$scope.object.open = false;
elem.on( "click", function() {
$scope.$apply( function() {
$scope.object.open = ! $scope.object.open;
});
});
}
}
和html:
<tr slide-toggle-row on="post">
<td>{{post.title}}</td>
<td>{{post.text}}</td>
</tr>
<tr>
答案 0 :(得分:2)
你不应该使用编译功能。尝试使用链接函数+ $ compile服务来注入与范围对象正确连接的HTML:
return {
restrict: 'A',
scope: {
object: '=on'
},
link: function(scope, elem) {
var td = angular.element('<td></td>'),
closeRow = angular.element('<i class="fa fa-arrow-circle-right" ng-if="!object.open"></i>'),
openRow = angular.element('<i class="fa fa-arrow-circle-down" ng-if="object.open"></i>');
td.append(closeRow).append(openRow);
$compile(td)(scope);
elem.append(td);
scope.object.open = false;
elem.on("click", function() {
scope.$apply(function() {
scope.object.open = !scope.object.open;
});
});
}
}