0

I have a function inside my controller that adds a piece of HTML (an input) into the DOM.

var myApp = angular.module('myApp', []);
myApp.controller('appController', ['$scope',
  function($scope) {
    $scope.data = {};
    $scope.data.value = null;

    $scope.addHtml = function() {
      $('#section').html('<input type="checkbox" value="false" name="checkbox", ng-model="data.value">');
    }

    $scope.logData = function() {
      alert($scope.data.value);
    }

  }
]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<html ng-app="myApp">

<head>
</head>

<body ng-controller="appController">
  <div id="buttons">
    <button ng-click="addHtml()">Add HTML</button>
    <button ng-click="logData()">Alert Val</button>
  </div>

  <div id="section">
  </div>
</body>

</html>

When I run $scope.addHtml(), it successfully adds the input into the #section div. However, the ng-model doesn't bind to the $scope.data.

What's a simple but effective way of binding this input value to the $scope.data after a DOM change?

davidvnog
  • 654
  • 2
  • 11
  • 33
  • 1
    Well you are just totally using angular wrong by injecting things in DOM with jQuery. The proper thing would be update your data model and let angular manage the DOM for you – charlietfl Apr 09 '15 at 15:18
  • I am new to AngularJS, can you give me some directions? – davidvnog Apr 09 '15 at 15:22
  • 1
    Go through the tutorial on docs site end to end. Take jQuery right out of your page when learning angular. Also be sure to read this post thoroughly [thinking-in-angularjs-if-i-have-a-jquery-background](http://stackoverflow.com/questions/14994391/thinking-in-angularjs-if-i-have-a-jquery-background) – charlietfl Apr 09 '15 at 15:23

0 Answers0