Search code examples
angularjsangularjs-ng-clicksetattribute

angularjs ng-click "How can I use javascript's setAttribute() to create ng-click attribute with some function"


I would like to be able to select a button using querySelector and set an attribute of "ng-click=doSomething()"

I have tried selecting the button and then setAttribute("ng-click", "doSomething()") but its not working

my DOM:

<body>
    <div ng-app="myApp" ng-controller="mainCtrl">

        <button id="myBtn">click Me</button>

    </div>
    <script src="./js/app2.js"></script>
</body>

my javascript:

(function() {
    "use strict";

    angular.module("myApp", []).controller("mainCtrl", mainCtrl);

    /** @ngInject */
    function mainCtrl($scope) {

      init();
      function init() {
          $scope.doSomething = () => {
              console.log("doing something");
          }
          let btn = document.querySelector('#myBtn');
          btn.setAttribute("ng-click", "doSomething()");
      }
    }
  })();

when I click the button it should console log something.


Solution

  • (function() {
        "use strict";
            var btn = document.querySelector('#myBtn');
        btn.setAttribute("ng-click", "doSomething()");
        angular.module("myApp", []).controller("mainCtrl", mainCtrl);
            function mainCtrl($scope){
            $scope.doSomething = function(){
            alert('abc');
          }
    
        }
        angular.bootstrap(document, ['myApp']);         
    })();
    

    Please check the JSFiddle , the difference is you have to modified the html before angular bootstrapped so your modified html and js code can be compiled properly. Here is a AngularJS Developer Guide - Bootstrap with more infomation of angularjs bootstrap