javascript - AngularJs指令多次发出

标签 javascript angularjs

我想多次使用我的指令。每次单击按钮时,我都希望模板相应更新。 最初 $scope.item 包含 item.id = 1。因此它显示为

enter image description here

接下来,当我单击按钮时,我将 item.id 更改为 4。现在结果如下。

enter image description here

但是正如您所看到的,最初显示的 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/

相关文章:

javascript - 轮播标题在更改幻灯片 Bootstrap 时不会消失

javascript - 在javascript中循环和存储不同长度的obj

javascript - 如何使用 highstocks 在 Highcharts 中用我们自己的来自 API 的时间戳数据替换 x 轴

javascript - 如何删除这个 HTML?

javascript - AngularJS - 加载我的指令突然不起作用?

javascript - 如何在没有表长度的情况下创建和递增数字

javascript - toExpontial 在 React Native 中未定义

javascript - Angular 中的 Kendo 多日历

使用国际键盘输入印地语的 JavaScript 库

javascript - XMLHttpRequest 无法加载 http 无 Access-Control-Allow-Origin header angularjs