所遇问题:
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也是一样处理。