Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript AngularJS An Introduction to Directives Directives: $observe

Fareez Ahmed
Fareez Ahmed
12,728 Points

Stuck!

Hi, what's wrong with this code, could someone explain the logic behind it?

I wish the challenges here matched up the level of depth/examples in the videos.

angular.module('myApp', [])
  .controller('myController', function ($scope) {
    $scope.title = 'My embedded title';
  })
  .directive('treehouseCourse', function () {
    return {
      link: function ($scope, $element, $attrs) {

        $attrs.$observe( courseTitle, function(){


        }){
          console.log( $scope.title );
        }

      }
    }
  });
index.html
<!DOCTYPE html>
<html ng-app="myApp">
<head>
  <title>Angular.js</title>
  <script src="js/angular.js"></script>
  <script src="app.js"></script>
</head>
<body ng-controller="myController">

  <div treehouse-course course-title="{{title}}"></div>

</body>
</html>

2 Answers

Chris Shaw
Chris Shaw
26,676 Points

Hi Fareez Ahmed,

You seem to have the general gist of what's required but some incorrect code within your observer, those errors are as follows:

  1. You're observing treehouseCourse which isn't a valid attribute for the treehouseCourse directive
  2. You're not logged the value of newValue to console.log
  3. You don't need your isInitialized code as the directive has already been initialized.

See the below.

$attrs.$observe('courseTitle', function(newValue, oldValue) {
  console.log(newValue);
});

One thing to remember is whenever an attribute is mentioned as course-title for example we need to remove the hyphen and camel case the attribute starting with the first letter of each additional word which in this case results in courseTitle.

Happy coding!

Chris Shaw
Chris Shaw
26,676 Points

You're welcome.