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 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,676 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,676 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.