为什么我不能在AngularJS中使用ng-show inside指令

Why i cannot use ng-show inside directive in AngularJS?

本文关键字:ng-show inside 指令 不能 AngularJS 为什么      更新时间:2023-09-26

我试图使一个元素,显示它的内容时,点击它:有很多方法可以做到这一点。我想在指令内做。为什么不工作?

http://plnkr.co/edit/Y13bcD7Ikuk6pERM9Mm8?p =

预览HTML:

<ez-option title="option 1">
        Option 1 inside
        <input ng-model="x">{{x}}
    </ez-option>
    <ez-option title="option 2">
        Option 2 inside
   </ez-option>
JavaScript:

directive('ezOption',function(){
    return {
        template:'<li></li><div ng-show=selected ng-transclude class=body></div>',
        link:function ($scope,iElement,iAttrs,controller,tanscludeFn){
            iElement.find('li').html(iAttrs.title)
            iElement.find('li').on('click',function(){
              $scope.selected=true
            })
        },
        scope:true,
        transclude:true
    }
})

这是因为angular没有意识到点击事件的作用域变化。要让它知道,你应该这样做

            iElement.find('li').on('click',function(){
              $scope.$apply(function() {
                $scope.selected=true;
              })
            })

或者,你可以使用angular的ng-click来代替

m.directive('ezOption',function(){
    return {
        template:'<li ng-click="selected=true"></li><div ng-show=selected ng-transclude class=body></div>',
        link:function ($scope,iElement,iAttrs,controller,tanscludeFn){
            iElement.find('li').html(iAttrs.title);
        },
        controller:function($scope){
          $scope.selected=false
        },
        transclude:true
    }
})

既然你的事件在angular之外…这是一个DOM事件,你需要告诉angular作用域的变化,这样它才能运行摘要。

使用$scope.$apply()。如果你使用像ng-click这样的核心事件指令,这是由angular在内部完成的。

   iElement.find('li').on('click',function(){
        $scope.selected=true;
        $scope.$apply();
    });

因此,在使用你自己的

之前,你通常最好使用大量的核心angular事件指令。