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

Ronnie Barua
Ronnie Barua
17,665 Points

Can't solve this

Write the code to call console.log with the value of the course-title attribute every time it changes.

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

        $attrs.$observe(courseTitle);

          console.log(courseTitle);

        // YOUR CODE HERE
        }

    }
  });
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

$observe takes in two parameters - key as a string and a function. The key would refer to the attribute you're monitoring or observing for changes. Where function is a callback every time a change is made. The new value of the attribute is passed in as a parameter to the function parameter.

The result should look like the following:

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(value){
          console.log(value);
        });

      }
    }
  });
Ronnie Barua
Ronnie Barua
17,665 Points

Thank you so much Juan for explaining because I'm just a bit confuse here as I progress.