angularJS控制器ng-controller裡獲取不到input標籤裡ng-model的值
阿新 • • 發佈:2019-01-04
所遇問題:
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也是一樣處理。