Angular:将变量传递给指令

Angular: Pass variable to directive

我希望将变量从控制器传递到我创建的指令:

HTML

<div class="dropup inline-block" ng-repeat="event in video.events">
    <event video="video"></event>
</div>

指令

.directive("event", function() {
    return {
      restrict: "E",
      replace: true,
      scope:{
        video: '=videoObject'
      },
      template: '<a class="btn btn-default event-margin" ng-style="{color: video.iconColor, float: floatEvents}" type="button"  data-title="{{event.title}}"><span class="fa fa-fw {{event.icon}}"></span></a>',
      link: function(scope, elm, attrs) {
        elm
        .on('mouseenter', function() {
          elm.css('background-color', scope.video.color);
          elm.css('color','#FFFFFF');
        })
        .on('mouseleave', function() {
          elm.css('background-color','#FFFFFF');
          elm.css('color', scope.video.color);
        });
      }
    };

问题是当我在返回的 dict 属性中添加 scope 时它停止工作。

所以想法是当我将鼠标放在元素上时改变元素的颜色,值为video.color,$中的一个变量控制器的范围。

我一直在其他帖子中寻找答案,但它们不起作用:

如果视频是对象则添加 video: '=video',
如果视频是字符串,则添加 video: '@video'

.directive("event", function() {
    return {
      restrict: "E",
      replace: true,
      scope:{
        video: '=video'
      },
      template: '<a class="btn btn-default event-margin" ng-style="{color: video.iconColor, float: floatEvents}" type="button"  data-title="{{event.title}}"><span class="fa fa-fw {{event.icon}}"></span></a>',
      link: function(scope, elm, attrs) {
        elm
        .on('mouseenter', function() {
          elm.css('background-color', scope.video.color);
          elm.css('color','#FFFFFF');
        })
        .on('mouseleave', function() {
          elm.css('background-color','#FFFFFF');
          elm.css('color', scope.video.color);
        });
      }
    };

好的,我找到了解决办法, video 是控制器的范围变量。在返回的字典中将范围设置为 false 允许指令访问控制器的范围。

在这个网站上有解释:https://www.undefinednull.com/2014/02/11/mastering-the-scope-of-a-directive-in-angularjs/

When scope is set to “true”, AngularJS will create a new scope by inheriting parent scope ( usually controller scope, otherwise the application’s rootScope ). Any changes made to this new scope will not reflect back to the parent scope. However, since the new scope is inherited from the parent scope, any changes made in the Ctrl1 ( the parent scope ) will be reflected in the directive scope.

When scope is set to “false”, the controller Ctrl1 and directive are using the same scope object. This means any changes to the controller or directive will be in sync.