programing tip

jQuery로 입력 값을 설정 한 후 각도 모델 업데이트

itbloger 2020. 6. 5. 20:16
반응형

jQuery로 입력 값을 설정 한 후 각도 모델 업데이트


이 간단한 시나리오가 있습니다.

jQuery의 val () 메소드에 의해 값이 변경되는 입력 요소.

jQuery가 설정 한 값으로 각도 모델을 업데이트하려고합니다. 간단한 지시문을 작성하려고했지만 원하는 것을하지 않습니다.

지시어는 다음과 같습니다.

var myApp = angular.module('myApp', []);
myApp.directive('testChange', function() {
    return function(scope, element, attrs) {        
        element.bind('change', function() {
            console.log('value changed');
        })
    }
})

이것은 jQuery 부분입니다.

$(function(){
    $('button').click(function(){
        $('input').val('xxx');
    })
})

그리고 html :

<div ng-app="myApp">
    <div ng-controller="MyCtrl">
        <input test-change ng-model="foo" />
        <span>{{foo}}</span>
    </div>
</div>

<button>clickme</button>

내 시도와 바이올린은 다음과 같습니다.
http://jsfiddle.net/U3pVM/743/

누군가 올바른 방향으로 나를 가리킬 수 있습니까?


ngModel은 "입력"이벤트를 수신하므로 코드를 "수정"하려면 값을 설정 한 후 해당 이벤트를 트리거해야합니다.

$('button').click(function(){
    var input = $('input');
    input.val('xxx');
    input.trigger('input'); // Use for Chrome/Firefox/Edge
    input.trigger('change'); // Use for Chrome/Firefox/Edge + IE11
});

이 특정 동작에 대한 설명을 보려면 " AnularJS가 내부적으로 'onclick', 'onchange'와 같은 이벤트를 어떻게 포착합니까? "라는 답변을 확인하십시오.


그러나 불행히도 이것이 당신이 가진 유일한 문제는 아닙니다. 다른 게시물 주석에서 지적했듯이 jQuery 중심 접근 방식은 명백히 잘못되었습니다. 자세한 내용은이 게시물을 살펴보십시오 . jQuery 배경이있는 경우 어떻게“AngularJS를 생각합니까?” ).


이것이 누군가에게 유용하기를 바랍니다.

jQuery('#myInputElement').trigger('input')각도 앱 에서 이벤트 를받을 수 없었 습니다.

그러나 나는 angular.element(jQuery('#myInputElement')).triggerHandler('input')데리러 올 수 있었다 .


jQuery가 필요하다고 생각하지 않습니다.

대신 $ watchng-click을 사용할 수 있습니다

<div ng-app="myApp">
  <div ng-controller="MyCtrl">
    <input test-change ng-model="foo" />
    <span>{{foo}}</span>

    <button ng-click=" foo= 'xxx' ">click me</button>
    <!-- this changes foo value, you can also call a function from your controller -->
  </div>
</div>

컨트롤러에서 :

$scope.$watch('foo', function(newValue, oldValue) {
  console.log(newValue);
  console.log(oldValue);
});

다음과 같이 특정 입력 모델의 범위를 업데이트하려면 다음 코드를 사용해야합니다

$('button').on('click', function(){
    var newVal = $(this).data('val');
    $('select').val(newVal).change();

    var scope = angular.element($("select")).scope();
    scope.$apply(function(){
        scope.selectValue = newVal;
    });
});

inputjQuery로 이벤트를 트리거 한 수락 된 답변이 효과가 없었습니다. 이벤트를 작성하고 기본 JavaScript로 디스패치하는 것이 트릭입니다.

$("input")[0].dispatchEvent(new Event("input", { bubbles: true }));

액션 버튼에 리스너를 추가하여 컨트롤러 초기화 만 수정했습니다.

$(document).on('click', '#action-button', function () {
        $timeout(function () {
             angular.element($('#input')).triggerHandler('input');
        });
});

내 경우에는 다른 솔루션이 작동하지 않았습니다.


나는 여기에 대답하는 것이 약간 늦다는 것을 알고 있지만 어쩌면 나는 하루를 한 번 구할 수도 있습니다.

나는 같은 문제를 다루고있다. jQuery에서 입력 값을 업데이트하면 모델이 채워지지 않습니다. 트리거 이벤트를 사용해 보았지만 결과가 없습니다.

내가 한 일이 당신의 하루를 구할 수 있습니다.

HTML에서 스크립트 태그 내에 변수를 선언하십시오.

처럼:

<script>
 var inputValue="";

// update that variable using your jQuery function with appropriate value, you want...

</script>

일단 아래의 각도 서비스를 사용하여 그렇게했습니다.

이제 동일한 컨트롤러 범위에서 호출 된 getData 함수 아래에 원하는 값이 제공됩니다.

var myApp = angular.module('myApp', []);

app.controller('imageManagerCtrl',['$scope','$window',function($scope,$window) {

$scope.getData = function () {
    console.log("Window value " + $window.inputValue);
}}]);

I've written this little plugin for jQuery which will make all calls to .val(value) update the angular element if present:

(function($, ng) {
  'use strict';

  var $val = $.fn.val; // save original jQuery function

  // override jQuery function
  $.fn.val = function (value) {
    // if getter, just return original
    if (!arguments.length) {
      return $val.call(this);
    }

    // get result of original function
    var result = $val.call(this, value);

    // trigger angular input (this[0] is the DOM object)
    ng.element(this[0]).triggerHandler('input');

    // return the original result
    return result; 
  }
})(window.jQuery, window.angular);

Just pop this script in after jQuery and angular.js and val(value) updates should now play nice.


Minified version:

!function(n,t){"use strict";var r=n.fn.val;n.fn.val=function(n){if(!arguments.length)return r.call(this);var e=r.call(this,n);return t.element(this[0]).triggerHandler("input"),e}}(window.jQuery,window.angular);

Example:

// the function
(function($, ng) {
  'use strict';
  
  var $val = $.fn.val;
  
  $.fn.val = function (value) {
    if (!arguments.length) {
      return $val.call(this);
    }
    
    var result = $val.call(this, value);
    
    ng.element(this[0]).triggerHandler('input');
    
    return result;
    
  }
})(window.jQuery, window.angular);

(function(ng){ 
  ng.module('example', [])
    .controller('ExampleController', function($scope) {
      $scope.output = "output";
      
      $scope.change = function() {
        $scope.output = "" + $scope.input;
      }
    });
})(window.angular);

(function($){  
  $(function() {
    var button = $('#button');
  
    if (button.length)
      console.log('hello, button');
    
    button.click(function() {
      var input = $('#input');
      
      var value = parseInt(input.val());
      value = isNaN(value) ? 0 : value;
      
      input.val(value + 1);
    });
  });
})(window.jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div ng-app="example" ng-controller="ExampleController">
  <input type="number" id="input" ng-model="input" ng-change="change()" />
  <span>{{output}}</span>
  <button id="button">+</button>
</div>


If you are using IE, you have to use: input.trigger("change");


add .change() after setting the value.

example:('id').val.('value').change();

also don't forget to add onchange or ng-change tag in html


I did this to be able to update the value of ngModel from the outside with Vanilla/jQuery:

function getScope(fieldElement) {
    var $scope = angular.element(fieldElement).scope();
    var nameScope;
    var name = fieldElement.getAttribute('name');
    if($scope) {
        if($scope.form) {
            nameScope = $scope.form[name];
        } else if($scope[name]) {
            nameScope = $scope[name];
        }
    }
    return nameScope;
}

function setScopeValue(fieldElement, newValue) {
    var $scope = getScope(fieldElement);
    if($scope) {
        $scope.$setViewValue(newValue);
        $scope.$validate();
        $scope.$render();
    }
}

setScopeValue(document.getElementById("fieldId"), "new value");

참고URL : https://stackoverflow.com/questions/17109850/update-angular-model-after-setting-input-value-with-jquery

반응형