angular.js - 關于指令link 中的創建變量問題
問題描述
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);}); }} })
如問題所示我現在,在link創建一個變量show,這個show用在模板表示是否hide可是 scope.show一直顯示true?不知道問題出現在哪里求賜教給位!謝謝但是console.log(scope.show)是同步改變的啊
問題解答
回答1:改:
elem.find('p').on('click',function(){ scope.show=!scope.show; scope.$apply();});
補充:
看文檔
文檔說了,如果是controller里的同步操作,或者是通過$http、$timeout、$interval的異步操作,scope.$apply()是自動執行的(Angular幫你做了)。但你這里顯然不符合條件,你使用了DOM API,所以需要手動顯示的調用一下scope.$apply()
文檔地址: scope
回答2:謝謝指教,看了文檔ng 自己很多自己的方法都會觸發apply,dom,累死settimeout的操作不會觸發apply
相關文章:
1. docker images顯示的鏡像過多,狗眼被亮瞎了,怎么辦?2. 關docker hub上有些鏡像的tag被標記““This image has vulnerabilities””3. docker-machine添加一個已有的docker主機問題4. css - 求推薦適用于vue2的框架 像bootstrap這種類型的5. Span標簽6. SessionNotFoundException:會話ID為null。調用quit()后使用WebDriver嗎?(硒)7. android新手一枚,android使用httclient獲取服務器端數據失敗,但是用java工程運行就可以成功獲取。8. css - 關于div自適應問題,大家看圖吧,說不清9. redis啟動有問題?10. java - Collections類里的swap函數,源碼為什么要新定義一個final的List型變量l指向傳入的list?
