AngularJS相同的元素,$编译多个指令:multidir ERROR [英] AngularJS multiple directives on same element, $compile:multidir ERROR

查看:661
本文介绍了AngularJS相同的元素,$编译多个指令:multidir ERROR的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是plunkr:
http://plnkr.co/edit/CzcVzKSvpKJTuTKARVJz?p=$p$pview

Here is the plunkr: http://plnkr.co/edit/CzcVzKSvpKJTuTKARVJz?p=preview

这是我简单的code:

and this is my simple code:

.directive('ngB', [function () {
    return {
      'restrict': 'A',
      'scope': {
        'ngB': '='
      },
      'link': function($scope, el) {

        var clss = 'b'
          , go = function () {

            if ($scope.ngB) {

              el.removeClass('a');
              el.addClass(clss);
            } else {
              el.removeClass(clss);
            }
          };

        $scope.$watch('ngB', function () {
          go();
        });
      }
    };
  }])
  .directive('ngF', [function () {
    return {
      'restrict': 'A',
      'scope': {
        'ngF': '='
      },
      'link': function($scope, el) {

        var clss = 'f'
          , go = function () {
            if ($scope.ngF) {

              el.removeClass('a');
              el.addClass(clss);
            } else {
              el.removeClass(clss);
            }
          };

        $scope.$watch('ngF', function () {
          go();
        });
      }
    };
  }]);


  //view.html
  <span ng-b="2 > 1" ng-a="1 > 2">here</span>

它返回控制台此错误: https://docs.angularjs.org/error/ $编译/ multidir

我怎样才能解决这个问题,而不从elmeent取出指令之一

How can i fix this without removing one of the directives from the elmeent

感谢您了很多。

推荐答案

正如上面所说,你不能有两个指令创建多个领域,无论是分离还是小孩,在相同的元素。

As suggested above, you cannot have two directives creating multiple scopes, whether isolate or child, on the same element.

您并不总是需要一个分离的范围。

You don't always need an isolate scope.

如果你正在做的是观察一个属性值的更改

if all you are doing is observing a change in an attribute value:

<span ng-f="{{1 < foo}}"></span>

然后,你可以拿起与 ATTRS的变化$观察

link: function(scope, element, attrs){
  attrs.$observe("ngF", function(v){
     // do something
  });
}

不过,如果你是看在模型值的更改赋予属性或前pression结果

If, however, you are watching for a change in the model value assigned to the attribute or an expression result

<span ng-f="foo"></span>
<span ng-f="foo === 10"></span>

这在我看来是这样

,你可以使用 $解析服务和$看以价值为导向的变化。

which seems to me to be the case, you can use $parse service and $watch for changes in the value.

link: function(scope, element, attrs){
   var parsed = $parse(attrs.ngF);
   scope.$watch(function(){
      return parsed(scope);
   },
   function(v){
     // do something
   });
}

这篇关于AngularJS相同的元素,$编译多个指令:multidir ERROR的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆