我想多次使用我的指令。每次单击按钮时,我都希望模板相应更新。 最初 $scope.item 包含 item.id = 1。因此它显示为
接下来,当我单击按钮时,我将 item.id 更改为 4。现在结果如下。
但是正如您所看到的,最初显示的 item1 已更改为 item4。
我想首先显示 item1,然后单击按钮时我想显示 item4 而不更改显示的初始值。我怎样才能实现这个目标?
我有以下指令
var app = angular.module('myApp', []);
app.directive('myDirective', function () {
return {
restrict: 'AE',
scope:true,
template: '<div>{{ item.id }}</div>'
}
});
我的 Controller
function MyCtrl($scope,$compile) {
$scope.item = {id: 'item1'};
$scope.hello = function() {
$scope.item = {id: 'item4'};
var dialogTextHTML ="<my-directive item ='item'></my-directive>"
var compiledDialogData = $compile(dialogTextHTML)($scope);
document.getElementById('mycontainer').appendChild(compiledDialogData[0]);
}
}
我的html
<div ng-controller="MyCtrl">
<button ng-click="hello()">
Click here
</button>
<div id='container'>
<my-directive item='item'></my-directive>
</div>
</div>
最佳答案
您应该尽量避免在 Controller 中进行 DOM 操作 - 这不是“Angular 方式”。
在这种情况下,我将在 <my-directive>
上使用 ng-repeat :
<my-directive ng-repeat="item in items" item='item'></my-directive>
然后每次点击时只需将一个项目添加到项目列表中:
function MyCtrl($scope, $compile) {
$scope.items = [];
var idCount = 0;
function addItem() {
idCount += 1;
$scope.items.push({
id: 'item' + idCount
});
}
$scope.hello = function() {
addItem();
}
addItem();
}
工作中的jsfiddle:https://jsfiddle.net/ub3zmo9s/1/
关于javascript - AngularJs指令多次发出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37566174/