0

I have the following code. Why doesn't the vm.name work? Why is the this inside the controller not being detected? Haven't I defined a closed scope for the directive?

What am I doing wrong?

var mod = angular.module('myApp', []);

mod.directive('myObj', myObject);

function myObject(){
  return {
      restrict: 'E',
      templateUrl: 'my-obj.html',
      scope: {},
      controller: myController
  };

  function myController(){
    var vm = this;

    vm.name="vfdfbdn";
  }
}
gespinha
  • 7,968
  • 16
  • 57
  • 91

4 Answers4

2

To use this in controller inside directive you need to use controllerAs: 'ctrl' but then in template you will need to prefix all name with {{ctrl.name}} or you can use $scope like:

function myController($scope) {
    $scope.name="vfdfbdn";
}
jcubic
  • 61,973
  • 54
  • 229
  • 402
1
function myObject(){
  return {
      restrict: 'E',
      template: '<div>{{c.name}}</div>',
      scope: {},
      controller: myController,
      controllerAs: 'c'
  };

  function myController(){
    var vm = this;

    vm.name="vfdfbdn";
  }
};

Please see this question to understand the things

Community
  • 1
  • 1
Naga Sandeep
  • 1,421
  • 2
  • 13
  • 26
0

Try this:

function myObject() {
    return {
        restrict: 'E',
        templateUrl: 'my-obj.html',
        scope: {},
        bindToController: true,
        controller: myController
    };
}


myController.$inject = ['$scope'];

function myController($scope){
  var vm = this;
  vm.name="vfdfbdn";}
Dilshod Zopirov
  • 710
  • 5
  • 10
0

You need to tell Angular how you are going to reference the this from the controller in the view.

function myObject(){
  return {
      restrict: 'E',
      templateUrl: 'my-obj.html',
      scope: {},
      controller: myController,
      controllerAs: 'ctrl'
  };
}

Now you can reference everything that you assigned to this, that you named vm in your controller with ctrl.

I used ctrl to show that there is no correlation between the name you use to refere to it in the view, setted with controllerAs and the name you give to this inside the controller function. It is a normal to reference different controllers with different controllerAs references so you can now which controller they refer to in the view.

Christian Gill
  • 514
  • 5
  • 21