Angular controller method gives an older scope value

What I'm trying to do:

I am creating a directive with an input text box. The onChange method also takes on value as a region parameter. The controller is untied over this directive, as you see in html, this controller provides an implementation of the onChange method and model for the value.

The problem I am facing:

see line console.log($scope.data): this statement prints the older value of the data object in the console.

Guess why this is happening.

Js codde

   angular.module('APP', [])
    .directive('txtInput', function () {
      return {
        restrict: "E",
        replace: true,
        scope: {
            value: '=',
            onChange: '&',
        },
        template: 
          '<div>'+
            '<input type="text" '+
              'ng-change = "onChange()" '+
              'ng-model="value" />'+
          '</div>',
    }
})
.controller('pageCtrl', function($scope) {
  $scope.data = {
    userPost: "sdsds",
  }
  $scope.onPostInputChange = function() {
    console.log($scope.data)
  }

})

Here is the HTML

<div ng-app='APP' ng-controller="pageCtrl">
    <txt-input 
        value="data.userPost"
        on-change="onPostInputChange()"> </txt-input>
  </div>

Also check copy on JSFIDDLE

+4
source share
1 answer

= & . , . . .

, , . , , .

angular.module('APP', [])
    .directive('txtInput', function () {
      return {
        restrict: "E",
        replace: true,
        scope: {
            value: '=',
            onChange: '&',
        },
        template: 
          '<div>'+
            '<input type="text" '+
              //'ng-change = "onChange()" '+
              //expose value as a local
              'ng-change = "onChange({$value: value}) '+
              'ng-model="value" />'+
          '</div>',
    }
})

HTML

<div ng-app='APP' ng-controller="pageCtrl">
    <txt-input 
        value="data.userPost"
        on-change="onPostInputChange($value)">
    </txt-input>
</div>

, :

angular.module('APP').controller('pageCtrl', function($scope) {
  $scope.data = {
    userPost: "sdsds",
  }
  $scope.onPostInputChange = function(value) {
    //console.log($scope.data)
    console.log(value);
  }
})

DEMO JSFiddle

+3

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


All Articles