简体   繁体   中英

Object initialize different in Angular directive than controller?

I've have run into an issue with object initialization differing whether the code is in a controller vs a directive link function. In the example code below, the "this" parameter being passed in the

prop: new Object(this)   

is a legit Object constructor when the code is run in the controller but is undefined when run in the directive. Why the difference in execution of the same code?

myapp.directive("myDir",function()
{
  var myDir = {
    link: function(scope,element,attrs)
    {
      var obj;

      obj = new Object({
        prop: new Object(this)
      });
    }
  }

  return myDir;
}


myapp.controller("MyCtrl",function($scope)
{
  var obj;

  obj = new Object({
    prop: new Object(this)
  });
}

I think your use of "this" in the declarations is the problem. Read up on How does the "this" keyword work? to make sure you understand how it works.

To me it looks like "this" will probably be set to the "myDir" variable in the directive, and the window object in the controller.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM