angularJS控制器ng-controller里获取不到input标签里ng-model的值

所遇问题:

html:ng-model="searchKey"

<div id="app-list" class="hidden" ng-controller="IndexController">

    <section class="media create-app-list" style="height: 120px">
        <aside class="media-body">
            <div class="navbar-form navbar-left form-inline" role="search">
                <div class="form-group">
                    <input type="text" class="form-control search-input" placeholder="搜索项目(AppId、项目名)"
            style="width: 200px"
            ng-model="searchKey" ng-change="changeSearchKey()" ng-focus="changeSearchKey()">
                </div>
            </div>
        </aside>
    </section>
</dev>

但是在js里changeSearchKey()的scope.searchKey取出来的是最开始初始值空串""

scope.changeSearchKey = function () {
    scope.copiedApps = [];
    var searchKey = scope.searchKey.toLocaleLowerCase();
    scope.sourceApps.forEach(function (app) {
        if (app.name.toLocaleLowerCase().indexOf(searchKey) > -1 || app.appId.toLocaleLowerCase().indexOf(searchKey) > -1) {
            scope.copiedApps.push(app);
        }
    });
    scope.shouldShowAppList = true;
};

原因:

scope不一样?

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

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

解决方法:

        解决ng-controller中ng-model值无效的问题,主要方法就是在绑定值时添加$parent标识

       ng-model="$parent.searchKey"

ng-if也是一样处理。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值