search

Home  >  Q&A  >  body text

angular.js - Regarding the issue of creating variables in the link directive

angular.module("myDirective",[])
    .directive("tabOne",function (){
        return{
            restrict:"E",
            replace:true,
            scope:{
                data:"=myData",
            },
            transclude:true,
            template:' <p ng-hide="show">'+
            '<p ng-repeat="x in data">'+
                '{{x}}'+
    '</p>'+
    '</p>',
            link:function(scope,elem,attr){
                scope.show=true;
               elem.find("p").on("click",function(){
                    scope.show=!scope.show;
                    console.log(scope.show);
                });
            }
        }
    })

As shown in the question, I am now creating a variable show in the link. This show is used in the template to indicate whether hide or scope.show always displays true?
I don’t know where the problem lies, please give me some advice! Thank you
But console.log (scope.show) changes synchronously

phpcn_u1582phpcn_u15822827 days ago721

reply all(2)I'll reply

  • 给我你的怀抱

    给我你的怀抱2017-05-15 17:05:33

    Changed:

    elem.find("p").on("click",function(){
        scope.show=!scope.show;
        scope.$apply();
    });

    Added:

    See the documentation

    The document says that if it is controller里的同步操作,或者是通过$http$timeout$interval的异步操作,scope.$apply()是自动执行的(Angular帮你做了)。但你这里显然不符合条件,你使用了DOM API,所以需要手动显示的调用一下scope.$apply()

    Document address: scope

    reply
    0
  • 漂亮男人

    漂亮男人2017-05-15 17:05:33

    Thank you for the advice. After reading the documentation, many of my own methods will trigger apply, dom, and the exhaustive settimeout operation will not trigger apply

    reply
    0
  • Cancelreply