U
U
Umid2015-08-16 11:57:12
Angular
Umid, 2015-08-16 11:57:12

Why doesn't Angular work with a loop?

When writing a loop in js, all Angular script and attributes are turned off, and only the loop itself is displayed.
How can I fix it?
Whole Script:

var myApp = angular.module("myApp" , []);

myApp.controller("firstCtrl", function($scope){
    $scope.name = "World";
});

myApp.controller('PhoneListCtrl', function($scope){
  $scope.phones  = [
    {'name' : 'Nexus',
     'snippet' : 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.',
     'status': true},
    {'name' : 'HTC',
   	 'snippet' : 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.',
   	 'status' : false},
   	{'name' : 'Huawei',
   	 'snippet' : 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.',
   	 'status' : true}
  ];

  var date = new Date();
  $scope.today = date;
       
      //Цикл
  myNumber = 10;
  function newFunc(number){
    newArray = new Array(number);
    for (var i = 0; i < newArray.length; i++) {
      newArray[i] = 'Number: ' + (i + 1) + '<br />';
      document.write(newArray[i]);
    };
  };
  newFunc(myNumber);
});

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexey Ukolov, 2015-08-16
@DarCKoder

As far as I understood from your description of the problem, the point is document.write - it simply overwrites everything that is on the page ( more ).
You need to write in the innerHtml of some specific element - like this :

var myNumber = 10;

function newFunc(number) {
    var el = document.getElementById('bar'),
        content = '';
    
    for (var i = 1; i <= number; i++) {
        content += 'Number: ' + i + '<br />';
    }
    
    el.innerHTML = content;
}

newFunc(myNumber);

And with arrays, it's better to work like this ( here's why ):
var myNumber = 10;

function newFunc(number) {
    var newArray = [],
          str;

    for (var i = 0; i < number; i++) {
        str = 'Number: ' + (i + 1) + '<br />';
        newArray.push(str);
        console.log(str);
    }
}

newFunc(myNumber);

This is provided that you really need this array later, and you do not use it as a crooked replacement for the usual for statement:
var myNumber = 10;

function newFunc(number) {
    for (var i = 1; i <= number; i++) {
        console.log('Number: ' + i + '<br />');
    }
}

newFunc(myNumber);

S
Sergey, 2015-08-16
Protko @Fesor

Here I look and wonder why you need an argular?
document.write is the cause of your problem. Just give it up. All this satan that you do in the controller can be done in the template (and you need to do it there).

<ul>
    <li ng-repeat="phone in phones">Number: {{$index + 1}}</li>
</ul>

In the controller, only work with data (for good, services work with data, and controllers simply delegate this duty to them, but apparently this is already difficult).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question