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 Extending Inputs Extending Inputs: Optional require

check is controller defined

can somebody help me with this task please? I dont get it :/

angular.module('treehouseCourse', [])
  .directive('sometimesTwoWay', function() {
    return {
      require: '?ngModel',
      link: function($scope,$element,$attrs,ngModelCtrl){}
<!DOCTYPE html>
<html ng-app="treehouseCourse">
  <script src="js/angular.js"></script>
  <script src="app.js"></script>

  <sometimes-two-way ng-model="course.description"></sometimes-two-way>


2 Answers

The controller should be the value passed to the parameter ngModelCtrl in the link function. It will either be defined (passed a value) or by default, will be undefined, as any parameter not passed into a function would be in JavaScript.

So you're essentially testing if ngModelCtrl equals undefined.

The simplest way to do that is a conditional with a logical NOT operator:

if (!ngModelCtrl) {
  // ngModelCtrl is undefined

OR of course, you can leave out the ! and check first to see if it is defined:

if (ngModelCtrl) {
  // ngModelCtrl is defined
} else {
  // ngModelCtrl is undefined

Hope that helps!

Thank you Iain :)

No problem. You should probably mark the answer as 'Best Answer' if it answered your question, that way other students know your question has been answered/closed.