Jorge A.
Jorge A.

Reputation: 55

AngularJs 1 issue with controller and bindings

I'm having an issue where placing ng-controller in a div, breaks the bindings that are inside of it. I'm a newbie with Angular so I must be doing something wrong, please help.

html:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" crossorigin="anonymous">
  <title>Third Excercise</title>
</head>
<body>

<div ng-app>
  {{"Hello World"}}
  <div ng-controller="FirstCtrl">
    <h1>{{ data.message + " world" }}</h1>
    <div ng-class="data.message">
      test
    </div>
  </div>
</div>

<!-- Imports -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js" charset="utf-8"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"
  integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS"
  crossorigin="anonymous" charset="utf-8"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.5/angular.min.js"
 charset="utf-8">
></script>
<!-- Local Files-->
<script src="js/third-excercise.js" charset="utf-8"></script>
</body>
</html>

js:

function FirstCtrl($scope) {
  $scope.data = {message : "Hello"};
  //$scope.data.message = "Hello";
}

I've pasted my code here: http://jsbin.com/yitezu/4/edit?html,js,output

Upvotes: 1

Views: 47

Answers (1)

step 1: Add a module to ng-app directive

<div ng-app="myApp">
  {{"Hello World"}}
  <div ng-controller="FirstCtrl">

    <h1>{{ data.message + " world" }}</h1>
    <div ng-class="data.message">
      test
    </div>
  </div>
</div>

step2: Register the controller in the module

angular.module('myApp', []);

angular.module('myApp')
.controller('FirstCtrl', FirstCtrl);

function FirstCtrl($scope) {
  $scope.data = {message : "Hello"}; 
}

Upvotes: 2

Related Questions