Changing the angle in the model only has a click somewhere

I am working on a search function using firebase and angular js. Basically, when I press the search key, I call the following function:

scope.suggestString = {};

    scope.search = function(){
        scope.suggestString = {};

        firebaseDb.ref("users")
        .orderByChild("Name")
        .startAt(scope.searchedString)
        .endAt(scope.searchedString + "\uf8ff")
        .on("value", function(snapshot) {
            snapshot.forEach(function(childSnapshot) {
                if(scope.suggestString.hasOwnProperty(childSnapshot.key) == false){
                    scope.suggestString[childSnapshot.key] = childSnapshot;
                }
            });
        });
    }

HTML:

<form>
    <input type="text" ng-model="searchedString" ng-keyup="search()">                   

    <ul>
       <li ng-repeat="(key,item) in suggestString">
         <a href="#/home/{{key}}">{{item.val().firstName}}</a>
      </li> 
    </ul>

</form>

The code works, the call goes to firebase and retrieves the entries, but I have to click somewhere in the input input field for the sentences to be displayed. I tried using scope. $ Apply (), but its not working. He says he already applies the area

+4
source share
3 answers

maybe you can use something like:

<input ng-model="searchedString" ng-model-options="{debounce: 1000}" type="text"> 

in an input field that will update ng-model (searchString) using the search string in the input element after a 1 second input delay.

After that you can put something like:

scope.$watch('searchedString', (newVal,oldVal)=>{
     scope.suggestString = {};

        if(scope.searchedString.length <3){
            return;
        }

        firebaseDb.ref("users")
        .orderByChild("Name")
        .startAt(scope.searchedString)
        .endAt(scope.searchedString + "\uf8ff")
        .on("value", function(snapshot) {
            snapshot.forEach(function(childSnapshot) {
                if(scope.suggestString.hasOwnProperty(childSnapshot.key) == false){
                    scope.suggestString[childSnapshot.key] = childSnapshot;
                }
            });
        });
});

, .

+2

Angular , . , , $evalAsync :

// ...
.on("value", function (snapshot) {
  scope.$evalAsync(function () {
    snapshot.forEach(function (childSnapshot) {
      if (scope.suggestString.hasOwnProperty(childSnapshot.key) == false) {
        scope.suggestString[childSnapshot.key] = childSnapshot;
      }
    })
  });
});

, scope.$apply , , .

firebase (, ) $q firebase. , Angular $q.

0

- , , .

-1

Source: https://habr.com/ru/post/1686060/


All Articles