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 Two-Way Data Binding Two-Way Binding: ngModelCtrl

I don't understand the ngModelCtrl and .directive method.. How do I complete this code challenge?

I don't understand the ngModelCtrl and .directive method..

How do I complete this code challenge?

app.js
angular.module('myApp', [])
.controller('myController', function($scope) {
  $scope.user = {
    name: 'Alex'
  };
})
.directive('myDirective', function () {
  return {
    require: 'ngModel',
    priority: 1,
    link: function ($scope, $element, $attrs, ngModelCtrl) {

      // YOUR CODE HERE
      function(ngModelCtrl) {
        console.log(ngModelCtrl);
      }

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

  <p>Hello {{user.name}}</p>
  <input type="text" ng-model="user.name" />
  <div my-directive ng-model="user.name"></div>

</body>
</html>

4 Answers

Chris Shaw
Chris Shaw
26,662 Points

Hi Hardik,

As stated in the video we can retrieve values from the model using the $render function which notifies the model that the value of user.name has changed.

ngModelCtrl.$render = function() {
  console.log(ngModelCtrl.$viewValue);
};

Happy coding!

This is exactly what I did, when I run check work it says "Bummer you need a link function within your directive....

After refreshing the challenge 3 times. And putting the same code back in it works. Seems challenge is a bit buggy.

Yeah, I can't get the challenge to accept this answer no matter how many times I refresh.

Gavin Engel
Gavin Engel
542 Points

I also had trouble with this question. I think it should be split into 2 questions.

Anyone ever find out an answer to this? I entered Chris's code in the "code here" spot and it fails. "You need to call console.log within the link function of the 'treehouseCourse' directive."

Chris Shaw
Chris Shaw
26,662 Points

Hi Adam,

I just tried it and it worked perfectly, if it continues to fail try the code challenge in another browser.

Thanks Chris. I'm not sure what I was doing wrong, but it's working now.