Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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.