BlackMagma
BlackMagma

Reputation: 67

Cant understand why AngularJS is not producing expected results

here is my code:

<!DOCTYPE html>
<html>

<head>
<title> test </title>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
</head>

<body>

<h1> Section One </h1>

<div data-ng-app="secOne" data-ng-controller="personController"> <!-- data-ng-init="forename = 'John'" -->
    <p> What is your forename? <input type="text" data-ng-model="forename"> </p>
    <p> What is your surname? <input type="text" data-ng-model="surname"> </p>
    <p> Hello {{ forename }} {{ surname }} </p>
    <p> Enter a number: <input type="number" data-ng-model="numberOne"> </p>
    <p> Enter another number: <input type="number" data-ng-model="numberTwo"> </p>
    <p> Total of numbers: {{numberOne + numberTwo}}</p>
</div>

<h2> Section Two </h2>
<div data-ng-app="secTwo" ng-init="countries=['Australia', 'Rwanda', 'Chad', 'USA', 'UK', 'Peru', 'Japan', 'China', 'Brazil', 'Poland', 'Croatia']" data-ng-controller="controllerTwo">
    <p><input type="text" ng-model="test"></p>

    <ul>
        <li ng-repeat="x in countries | filter:test">
            {{ x.countries }}
        </li>
    </ul>
</div>


<script>
function personController($scope){
    $scope.surname = "Matthews"
}
</script>
</body>
</html>

Firstly, within section one it is printing out Hello {{forename}} {{surname}} even though earlier it was printing out what i typed into the boxes. e.g. If i typed in 'Eric' into forename and then 'Mingo' into surname it would return 'Hello Eric Mingo'.

Secondly in section two, for some weird reason, it prints out {{ x.countries }} so bizarre. even more weird that is working like 5 minutes ago.

Upvotes: 0

Views: 58

Answers (1)

m4t1t0
m4t1t0

Reputation: 5721

Your problem is that you have two apps in the same page. For example this code works for me:

<head>
<title> test </title>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
</head>

<body>

<h1> Section One </h1>

<div ng-app ng-controller="personController">
    <p> What is your forename? <input type="text" data-ng-model="forename"> </p>
    <p> What is your surname? <input type="text" data-ng-model="surname"> </p>
    <p> Hello {{ forename }} {{ surname }} </p>
    <p> Enter a number: <input type="number" data-ng-model="numberOne"> </p>
    <p> Enter another number: <input type="number" data-ng-model="numberTwo"> </p>
    <p> Total of numbers: {{numberOne + numberTwo}}</p>
</div>

<script>
function personController($scope){
    $scope.surname = "Matthews"
}
</script>
</body>
</html>

If you need two apps in the same page you can read this question: AngularJS Multiple ng-app within a page

Upvotes: 1

Related Questions