模板 html:
我在模板 seats.tpl.html 文件中有一个元素,如下所示:
<select id="guest_table">
<option tables="emptySeats"
ng-repeat="table in emptySeats" value="{{table.tableId}}">{{table.tableNumber}}</option>
</select>
Controller
在 Controller 中,我调用工厂从数据库获取值,实际上我将结果加载到 $scope.emptySeats 数组中,该数组使用 ng-repeat 创建到模板中:
factP3_GetEmptyChairs.getEmptyChairs({'data': {'id': 58}})
.then(function (result) {
**$scope.emptySeats = result.data;**
$log.info("Empty chairs list loaded.");
},
function (result) {
$('.loading').hide();
$log.error("Error: we could not get Empty seats list.");
});
指令:
在我的指令中,我使用参数templateUrl来调用模板文件以加载,到目前为止一切顺利,选择加载了值。
.directive('emptySeats',function(){
return {
restrict: 'AE',
replace: true,
scope:{tables :'='},
templateUrl: function(){
return 'assets/modules/part3/templates/emptySeats.tpl.html';
},
link:function(scope, element, attrs) {
//bind change on element
element.bind('change', function() {
alert("table changed");
});
}
}
我的问题是,每当我更改 $scope.emptySeats 数组值时,我都需要自动更新这些值,但我当前的代码不会发生这种情况。
我认为指令中遗漏了一些东西,它是编译的,它是观察的,它是 ngmodel 的,有人可以帮忙吗?
更新: 我调用一个函数从数据库获取新数据并将它们加载到选择元素
$scope.onClickHall = function (hall) {
var tmp = [];
//call service to load empty Seats
factP3_GetEmptyChairs.getEmptyChairs({'data': {'id': $scope.currentHall}})
.then(function (result) {
//$scope.emptySeats = result.data;
答:如果我在这里使用 $apply,我会得到:错误:$rootScope:inprog 行动已在进行中
$scope.$apply(function () {
$scope.emptySeats = result.data;;
});
tmp = result.data; //i use a temp array to pass it on timeout
$log.info("Empty chairs list loaded.");
},
function (result) {
$('.loading').hide();
$log.error("Error: we could not get Empty seats list.");
});
B.如果我使用 $timeout 函数并尝试更改数据,则什么也不会发生
$timeout(function() {
$scope.$apply(function () {
$scope.emptySeats = tmp;
});
}, 10);
}
最佳答案
最好使用模板文件来增强引导弹出窗口、工具提示等的功能。有两种类型的模板可用于此目的。
示例:
<script type="text/ng-template" id="myTemplate.html">
<h1>Hi</h1>
</script>
$http.get(templateURL)
的 ajax 调用
为了正确附加模板,指令定义应如下定义。请注意,使用 $compile
才能正确集成内容。这将确保内容正确集成到您的指令内容中。
下面是一个示例。
angular.module('myApp')
.directive('myPopover', function () {
var getTemplate = function () {
var template = '';
template = $templateCache.get("myTemplate.html");
}
return template;
};
return {
restrict: 'A',
transclude: true,
scope: {
text: '@myPopover'
},
link: function(scope, element, attrs) {
var popOverContent = getTemplate();
popOverContent = $compile("<div>" + popOverContent+"</div>")(scope);
var options = {
//title : title,
content : popOverContent,
placement : "right",
html : true,
date : scope.date,
trigger : "hover"
};
$(element).popover(options);
}
};
});
这是一个工作plunker .
关于javascript - 使用 templateUrl 更新指令元素值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31738926/