javascript - AngularJS 1.6 : Directive inside Directive Template works only first time

标签 javascript angularjs directive

我有一个指令“avatar”,它接受一个“用户”对象并显示用户的图像。

这很好用。

现在我有另一个指令“user”,它显示给定“user”对象的名称,并在其模板中包含该指令。

这有效......第一次。

当我更新“用户”对象时,只有名称发生变化,图像(头像)不会改变。

我的问题:我怎样才能使它工作?

头像指令:

(链接功能:如果用户对象确实有'ext'属性,则计算图像路径('src'),否则显示标准模板.jpeg)

directive('avatarSmall', function() {

  return {
    restrict: "E",
    replace: true,
    templateUrl: "scripts/directives/avatar/small.html",
    link: function(scope, element, attrs) {
      var r = "images/avatars/";
      var ext = scope.user.ext;
      r += ext != undefined && ext.length >= 3 ? scope.user.ID + "." + ext : "template.jpeg";
      scope.src = r;
    },
    scope: {
      user: '='
    }
  }
})

头像模板:

<div class="circle-wrapper-small">
  <img class="circle-img-small"
       ng-src="{{src}}">
</div>

用户指令:

directive('user', function($compile) {
  return {
    restrict: "E",
    replace: true,
    templateUrl: "scripts/directives/user/template.html",
    scope: {
      user: '='
    }
  }
})

用户模板:

<div>
  <div class="media-left">
    <avatar-small user="user" />
  </div>
  <div class="media-body">
    <h4 class="media-heading">{{user.name}} {{user.surname}}</h4>
    </h5>
  </div>
</div>

最佳答案

因为您的 avatar 指令的代码仅在指令 init 上执行。如果您想更新更改,您应该将 $broadcast 事件发送到您的指令,并在 $broadcast 事件上执行该代码。

有关 $emit$broadcast$on 事件的更多信息,您可以查看这篇文章:Usage of $broadcast(), $emit() And $on() in AngularJS

类似这样的事情:

父 Controller

$scope.user = {
  // object properties
}

// watch "$scope.user" for changes
$scope.$watch('user', function(newVal, oldVal){
    if(newVal !== oldVal) {
      // send new "$scope.user" to your directive
      $scope.$broadcast('userObjChanged', $scope.user);
    }
}, true);

在你的指令中

// catch event from parent's controller with new user object
$scope.$on('userObjChanged', function(event, data) {
  console.log(data); // here is the new user object from parent's scope
})

关于javascript - AngularJS 1.6 : Directive inside Directive Template works only first time,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45383524/

相关文章:

javascript - 如何使错误消息更快消失

javascript - 使用 Controller 作为语法的多个 angularjs 指令实例

javascript - TemplateUrl angularJS 不工作

javascript - 如何使用 JQuery/Javascript 编辑嵌套列表?

javascript - 使用 javascript/jquery 删除字符串的开头

javascript - Google Charts 外部 Javascript 问题

javascript - 如何在 Angular 中仅模拟特定的 http 资源(URL)

javascript - ng-repeat with form in angularjs

javascript - Angular 日期选择器

带有属性指令的 Angular 2 自定义状态