1

I have a simple directive like this:

myApp.directive('myDirective', function() {
  var controller = ['$scope',  function($scope) {
    function init() {
      this.name = "Sim";
      this.age = 6;
    }
    init();
  }];
  //define the directive object
  var directive = {};
  directive.controller = controller;

  directive.restrict = 'E';
  directive.templateUrl = "hello.html";
  directive.controllerAs= 'cus';//defining a name to the controller.
  return directive;
});

Inside my html template I want to reference controller variables like below (please note the controller above is referenced as cus):

<div>
  <div>Name: {{cus.name}}</div>
  <div> Age: {{cus.age}}</div>
</div>

Here is my plunk with the problem

Why is this snippet not working?

4
  • i can see that in your controller, you inject scope, but nothing is written to the scope? Commented May 16, 2016 at 10:11
  • I want to store the value in the controller object and not in its scope. toddmotto.com/digging-into-angulars-controller-as-syntax Commented May 16, 2016 at 10:15
  • 1
    apparently a while since i was working with angular ;) But the $scope should probably not be injected then, it doesnt change anything in your case though Commented May 16, 2016 at 10:16
  • Yes you are right In my real project i am using scope for another reason. I made a simplified snippet to show my case. I should have removed scope since i am not using it here. Commented May 16, 2016 at 10:23

1 Answer 1

2

The possible problem is the usage of 'this'. Instead of using 'this', use the controllerAs variable.

Ex:

var cus = this;

function init() {
      cus.name = "Sim";
      cus.age = 6;
    }

init();
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @Sarathy You nailed it I never realized that inside the init() this is referring the window. For those who may fall in similar trap here is the fixed plunk plnkr.co/edit/H9EoLR?p=preview.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.