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!

1 Answer 1

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! ";
    }
});
4
  • wow! thanks a lot! how can i do the same with some html elements with classes? $scope.hi += "<p class="sads"></p>"; Commented Jan 29, 2013 at 9: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 <span ng-bind="hi"></span> This works also for arrays: jsfiddle.net/dakra/U3pVM btw, I really recommend docs.angularjs.org/tutorial And if my answer solved your problem, please accept it :) Commented Jan 29, 2013 at 10:10
  • there seems to be a way: stackoverflow.com/questions/9381926/… but it's not the way angular is meant to be used. put your stuff in an array and then use docs.angularjs.org/api/ng.directive:ngRepeat Commented Jan 29, 2013 at 10:52
  • <div ng-bind-html-unsafe="hi"></div> solved the problem!! thank you very much! :) Commented Jan 29, 2013 at 11:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.