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. npm镜像站全新上线2. python - django 项目的 migrations 目录是否应该提交到 git3. python爬虫 - Python:网页爬取Ajax地址,结果与浏览器显示的不一致?4. html - 竖线怎么实现5. 怎么学好php6. javascript - 对象里的一些没用了的数据大家是怎么处理的~7. mysql - 如何高效的查询需要合并大数据表的操作8. peter_zhu 老师 想请教个问题?9. python - pandas读取中文的时候乱码 要如何解决?10. javascript - vue的element-ui(饿了吗UI) webpack打包时externals无法分离

网公网安备