How to notify AngularJS that a form has been filled externally by jQuery?

后端 未结 2 1726
长发绾君心
长发绾君心 2021-01-25 14:44

I have a page in AngularJS which has a form containing some fields. Upon loading that page, I want a bookmark which when clicked to fill the fields based on data in a configurat

相关标签:
2条回答
  • 2021-01-25 15:07

    The ng-model controller listens to the 'change' event.

    <input id="id" ng-model="$ctrl.text" />
    

    To trigger it from jQuery:

    $("#id").val("abcd").trigger("change");
    

    This will set the value of the input and trigger the ngModelController to update the model in the AngularJS framework.

    The DEMO

    $(function() {
      $("#bt").on("click", function() {
        $("#id").val("abcd").trigger("change");
      });
    })
    <script src="//unpkg.com/jquery"></script>
    <script src="//unpkg.com/angular/angular.js"></script>
    <body ng-app>
        <input id="id" ng-model="$ctrl.text" /><br>
        text={{$ctrl.text}}<br>
        <button id="bt">Click me</button>
    </body>


    Note

    It is important to load the jQuery library before the AngularJS library.

    From the Docs:

    To use jQuery, simply ensure it is loaded before the angular.js file.

    For more information, see AngularJS angular.element API Reference.

    0 讨论(0)
  • 2021-01-25 15:29

    Call $apply after the data has been entered.

    $scope.$apply()

    This is used to hook into angular's digest cycle when events occur outside of angular.

    From the Docs

    $apply() is used to execute an expression in AngularJS from outside of the AngularJS framework. (For example from browser DOM events, setTimeout, XHR or third party libraries). Because we are calling into the AngularJS framework we need to perform proper scope life cycle of exception handling, executing watches.

    0 讨论(0)
提交回复
热议问题