title: angularjs ng-click "How can I use javascript's setAttribute() to create ng-click attribute with some function"
body: <p>I would like to be able to select a button using querySelector and set an attribute of "ng-click=doSomething()" </p>
  
  <p>I have tried selecting the button and then setAttribute("ng-click", "doSomething()") but its not working</p>
  
  <p>my DOM:</p>
  
  <pre class="lang-html prettyprint-override"><code>&lt;body&gt;
      &lt;div ng-app="myApp" ng-controller="mainCtrl"&gt;
  
          &lt;button id="myBtn"&gt;click Me&lt;/button&gt;
  
      &lt;/div&gt;
      &lt;script src="./js/app2.js"&gt;&lt;/script&gt;
  &lt;/body&gt;
  </code></pre>
  
  <p>my javascript:</p>
  
  <pre><code>(function() {
      "use strict";
  
      angular.module("myApp", []).controller("mainCtrl", mainCtrl);
  
      /** @ngInject */
      function mainCtrl($scope) {
  
        init();
        function init() {
            $scope.doSomething = () =&gt; {
                console.log("doing something");
            }
            let btn = document.querySelector('#myBtn');
            btn.setAttribute("ng-click", "doSomething()");
        }
      }
    })();
  </code></pre>
  
  <p>when I click the button it should console log something.</p>