简体   繁体   English

如何在$ scope。$ apply上执行angular指令

[英]How to execute angular directive on $scope.$apply

I have a directive that controls an image displayed in the DOM: 我有一个指令来控制DOM中显示的图像:

summariesApp.directive('changePlus', function () {
    return function changePlus(scope, element, attr) {
        if (scope.$parent.Tab == "MultiVariant")            
            if (scope.$parent.multis[parseInt(attr.a)].show) {
                    element[0].src = 'Images/hide.png';
                }
                else {
                    element[0].src = 'Images/show.png';
                }
            }
            else {
                element[0].src = 'Images/show.png';
            }

            element.on('mousedown', function (event) {
                var imgName = event.target.src.split("/");
                if (imgName[imgName.length - 1] == 'show.png') {
                    event.target.src = 'Images/hide.png'
                }
                else {
                    event.target.src = 'Images/show.png'
                }
            });
        }
    });

The issue is that when I call a service I would like for this directive to run. 问题是,当我调用服务时,我希望该指令运行。 I thought that by using $scope.$apply, and having the digest cycle fire, this directive would be evaluated but it is not. 我认为通过使用$ scope。$ apply并启动摘要循环,可以评估此​​指令,但不是。 Is there any way for me to have the view reevaluate with the directives on $scope.$apply? 有什么办法让我用$ scope。$ apply上的指令重新评估视图?

I think you are looking for $scope.$watch : 我认为您正在寻找$ scope。$ watch:

   $scope.$watch('myModelProperty', function() {
       // do something
   });

   $scope.buttonClicked = function() {
      $scope.myModelProperty = "foo"; // This will trigger $watch expression
   };

But a best practice is to bind an attribute of your directive on your service. 但是,最佳实践是将指令的属性绑定到服务上。 Avoid as much as possible to use $apply and $watch. 避免使用$ apply和$ watch。

With attribute : 具有属性:

angular.module('myModule', []).directive('myDirective', function() {
  return {
    restrict: 'E',
    scope: {
      myVar: '=' // two ways data-binding
    },
    link: function(scope, element, attrs, controllers) {
      scope.myVar //myVar is available in your scope and is bind to your model
    },
    templateUrl: 'my-template.html'// myVar is available in your template and is bind to your model
  };
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM