0

I just started using angular.js, and it is pretty useful. I have searched a lot maybe with wrong keywords, but I wasn't able to find how to use angular.js's Data Binding in javascipt.

Here is the sample of the problem:

<form><select ng-model="frfiSzam" id="frfi-szam">
      <option>1</option><option>2</option><option>3</option><option>4</option><option>5</option><option>6</option><option>7</option><option>8</option><option>9</option><option>10</option> <option>11</option><option>12</option><option>13</option><option>14</option><option>15</option>
    </select></form>

    <div class="leir">

     <p class="fejl">{{frfiSzam}} férfi résztvevő</p>


     <script type="text/javascript"> 

    var x= '{{frfiSzam}}'
    var char = '';
    while (x--) {
        char += 'Hi!';
    }
    // write once
    document.write(char);

     </script>

So the thing is working ( the first part) except this one var x= '{{frfiSzam}}'. If I set it to a constant the code is working fine, so I think I need to update my x variable when the drop down value changes, but I do not know how to do it so the code works.

Thanks a lot!

Ivan Ferić
  • 4,545
  • 11
  • 34
  • 46
GeriTol
  • 126
  • 8

1 Answers1

2

You are looking for a watch: http://jsfiddle.net/6QG9r/

$scope.$watch('number', function(newValue, oldValue) {
    //this callback function gets executed whenever 'number' changes
    var x = newValue;
    $scope.hi = "";
    while (x--) {
        $scope.hi += "Hi! ";
    }
});
mb21
  • 28,026
  • 6
  • 96
  • 118
  • wow! thanks a lot! how can i do the same with some html elements with classes? `$scope.hi += "

    ";`
    – GeriTol Jan 29 '13 at 09:30
  • You'll have to learn to think a bit different with angular ;) i.e. DON'T write HTML with document.write() Instead, bind the information to a variable like $scope.hi and make use of it in the HTML template like This works also for arrays: http://jsfiddle.net/dakra/U3pVM/ btw, I really recommend http://docs.angularjs.org/tutorial/ And if my answer solved your problem, please accept it :) – mb21 Jan 29 '13 at 10:10
  • there seems to be a way: http://stackoverflow.com/questions/9381926/insert-html-into-view-using-angularjs but it's not the way angular is meant to be used. put your stuff in an array and then use http://docs.angularjs.org/api/ng.directive:ngRepeat – mb21 Jan 29 '13 at 10:52
  • solved the problem!! thank you very much! :) – GeriTol Jan 29 '13 at 11:05