美文网首页
angularJs——input框绑定ng-model后js获取

angularJs——input框绑定ng-model后js获取

作者: 王保全_1098 | 来源:发表于2020-04-22 14:25 被阅读0次

    angularJs——input框绑定ng-model后js获取不到问题

    搬运自:https://blog.csdn.net/fenglongmiao/article/details/81545993

    https://blog.csdn.net/Spearmint_/article/details/102470350?depth_1-utm_source=distribute.pc_relevant.none-task&utm_source=distribute.pc_relevant.none-task

    https://www.sheyingtg.com/detail/320191.html

    与其他指令一样,ng-controller指令也会创建一个子级作用域,因此,如果在ng-controller指令中添加了元素,并向元素属性增加 ng-model指令,那么ng-model指令对应的作用域属性子级作用域,而并非控制器注入的$scope作用域对象,这点在进行双向数据绑定时,需要引起注意。

    在ng-controller方式中,每个包含的元素都拥有自己的作用域,因此,复选框元素也拥有自己的scope作用域。相对于控制器作用域来说,这个作用域属于一个子级作用域,所以,如果它想绑定控制器中的变量值,必须添加parent标识,只有这样才能访问到控制器中的变量。

    scope.parent——指向scope的父作用域,在子级作用域中使用`scope.parent.name`,来获取对父级作用域的双向绑定。

    我的问题:初始化搜索关键字为空字符,控制器始终监听不到关键词输入的变化。

    解决方案:在绑定值时添加$parent标识

    html:

    <pre style="margin: 0px; padding: 0px; white-space: pre-wrap; overflow-wrap: break-word; font-family: "Courier New" !important; font-size: 12px !important;"><input type="text" ng-model="$parent.searchTxt" ng-change="listenTxt()"></pre>

    js:

    <pre style="margin: 0px; padding: 0px; white-space: pre-wrap; overflow-wrap: break-word; font-family: "Courier New" !important; font-size: 12px !important;">$scope.searchTxt = '';

    scope.listenTxt=function(){ console.log('searchTxt',scope.searchTxt);
    }</pre>

    同理,ng-if指令也会创建一个子级作用域,想要ng-model生效,需要在scope创建一个子对象才行

    ** 解决方式:**

    1.使用$parent

    2.使用ng-show(或ng-hide)可以间接解决这个问题。

    3.使用$scope创建一个子对象,如

    <pre style="margin: 0px; padding: 0px; white-space: pre-wrap; overflow-wrap: break-word; font-family: "Courier New" !important; font-size: 12px !important;">$scope.a = {num: '1'};

    </pre>

    <pre style="margin: 0px; padding: 0px; white-space: pre-wrap; overflow-wrap: break-word; font-family: "Courier New" !important; font-size: 12px !important;"><input type="text" ng-model="a.num"></pre>

    相关文章

      网友评论

          本文标题:angularJs——input框绑定ng-model后js获取

          本文链接:https://www.haomeiwen.com/subject/zqsiihtx.html