Ajlanclos Ajlanclos - 5 months ago 30
AngularJS Question

Angular 2-Way Binding

I have been having this issue with Controllers in Angular. I looked it up as much as possible, but I could not resolve the issue.

I am trying to implement a simple controller, but for the life of me, I cannot get the binding to work. It's not displaying my data. For example when I say,

{{ test }}
, I get just that, not the "Hello World!" string.



var app = angular.module('App', []);

app.controller('Hi', function($scope){
$scope.hello = "hello!";
});

app.controller('todoCtrl', ['$scope', '$http', function($scope, $http) {
$scope.test = "Hello World!";
$scope.formData = "";

$http.get('/api/todos')
.success(function(data) {
$scope.todos = data;
console.log(data);
})
.error(function(data) {
console.log('Error: ' + data);
});

$scope.createTodo = function() {
$http.post('/api/todos', $scope.formData)
.success(function(data) {
$scope.formData.text = "";
$scope.todos = data;
console.log(data);
})
.error(function(data) {
console.log('Error: ' + data);
});
};

$scope.deleteTodo = function(id) {
$http.delete('/api/todos/' + id)
.success(function(data) {
$scope.todos = data;
console.log(data);
})
.error(function(data) {
console.log('Error: ' + data);
});
};
}]);

<!DOCTYPE html>
<html ng-app="App">
<head>
<title>TodoX</title>
<meta name="viewport" content="width=device-width, initial-scale=1">

<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<!-- TodoX CSS -->
<link rel="stylesheet" type="text/css" href="stylesheets/style.css"/>
</head>
<body ng-controller="todoCtrl">
<div class="container">
<div class="row">
<div class="jumbotron text-center">
<h1>TodoX<span>{{todos.length}}</span>{{test}}</h1>
</div>
<div class="col-md-8">
<div class="list-group">
<div class="checkbox" ng-repeat="todo in todos | orderBy:date">
<label class="list-group-item">
<input type="checkbox"/> {{todo.text}}
</label>
</div>
</div>
</div>
<div class="col-md-4">
<form class="form-group">
<input type="text" class="form-control" ng-model="formData"/>
<input type="submit" ng-click="createTodo()" placeholder="Submit" class="form-control"/>
</form>
</div>
</div>
</div>

<!-- Angular JS -->
<script type="text/javascript" href="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
<!-- TodoX Core JS -->
<script type="text/javascript" href="core.js"></script>
</body>
</html>




Answer

I just executed your code while placing angular file link above the script tag, so that AngularJs is loaded before your script can call angular modules.

I think you're putting angular after your script which is why you are running into this issue. Your code works just fine. I tested it.

Put it like this

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
<script src="script.js"></script>

Here script.js will be your controller script.

Working fiddle