ngChange fires before value makes it out of isolate scope

前端 未结 2 2095
时光说笑
时光说笑 2021-01-05 03:57
//main controller
angular.module(\'myApp\')
.controller(\'mainCtrl\', function ($scope){
    $scope.loadResults = function (){
        console.log($scope.searchFilte         


        
2条回答
  •  误落风尘
    2021-01-05 04:46

    You answered your own question in the title! '=' is watched while '&' is not

    • Somewhere outside angular:

      input view value changes

    • next digest cycle:

      ng-model value changes and fires ng-change()

      ng-change adds a $viewChangeListener and is called this same cycle. See: ngModel.js#L714 and ngChange.js implementation.

      At that time $scope.searchFilter hasn't been updated. Console.log's old value

    • next digest cycle: searchFilter is updated by data binding.

    UPDATE: Only as a POC that you need 1 extra cycle for the value to propagate you can do the following. See the other anwser (@NewDev for a cleaner approach).

    .controller('mainCtrl', function ($scope, $timeout){
        $scope.loadResults = function (){
            $timeout(function(){
               console.log($scope.searchFilter);
            });
        };
    });
    

提交回复
热议问题