javascript – $emit或$将事件从控制器广播到指令AngularJS

栏目: 编程语言 · AngularJS · 发布时间: 7年前

内容简介:代码日志版权声明:翻译自:http://stackoverflow.com/questions/25878077/emit-or-broadcast-an-event-from-a-controller-to-a-directive-angularjs

我希望能够在事件发生时更改指令显示时通知指令.我知道指令只运行一次,所以我想知道我该怎么做.我也不确定是否应该使用$emit或$broadcast,是指令控制器的一个小孩吗?

例如,在我的控制器我有:

$rootScope.$emit(‘PHOTO_UPLOADED’,照片);

在我的指示中:

.directive('photo', [function () {
  return {
    restrict: 'EA',
    scope: {user: '='},
    replace: true,
    template: '<div id="{{user.id}}"></div>',
    link: function ($scope, element, attrs) {
      var thumbnail = ($scope.user && $scope.user.image) 
        ? $scope.user.image
        : '/default.png';

      element.css('background-image', 'url(' + thumbnail + ')');

      $rootScope.$on('PHOTO_UPLOADED', function(event, data) {
         thumbnail = data;
      });
    }
  };
}])

我试图这样做,但没有发生任何事情,缩略图没有更新,因为指令已经运行.

使用$broadcast.这将播放事件到儿童范围.以下是使用广播将数据发送到父控制器的指令的示例:

http://jsfiddle.net/smaye81/q2hbnL5b/6/

代码日志版权声明:

翻译自:http://stackoverflow.com/questions/25878077/emit-or-broadcast-an-event-from-a-controller-to-a-directive-angularjs


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Rework

Rework

Jason Fried、David Heinemeier Hansson / Crown Business / 2010-3-9 / USD 22.00

"Jason Fried and David Hansson follow their own advice in REWORK, laying bare the surprising philosophies at the core of 37signals' success and inspiring us to put them into practice. There's no jarg......一起来看看 《Rework》 这本书的介绍吧!

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

MD5 加密
MD5 加密

MD5 加密工具

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具