Jamesla
Jamesla

Reputation: 1408

Databinding to a controller inside a directive in angular

I'm new to angular and have the following directive:

angular.module('myApp')
  .directive('myDirective', function () {
    return {
      templateUrl: '/views/partial-views/partial.html',
      restrict: 'E',
      controller : function(){
        age : '5'
      },
      controllerAs : 'myCtrl'
    };
  });

I want to include the age on my page inside partial.html which looks like this:

<div ng-app="myApp" ng-controller="myCtrl as s">
    {{s.age}}
</div>

However I am getting the following error:

Error: [ng:areq] Argument 'myCtrl' is not a function, got Object

Can anybody tell me what I'm doing wrong?

Upvotes: 0

Views: 57

Answers (2)

Aviro
Aviro

Reputation: 2155

What Chandermani mentioned is absolutely correct. To be more precised, it can be written as,

Directive Definition

angular.module('myApp')
    .directive('myDirective', function () {
        return {
            templateUrl: '/views/partial-views/partial.html',
            restrict: 'E',
            controller: ['$scope', function($scope){
                $scope.age = '5'
            }]
    };
})

Usage

<div ng-app="myApp">
    <my-directive>
    {{age}}
    </my-directive>
</div>

However, there's no meaning of defining a directive here. You can just use a controller definition to fulfill the same action.

Upvotes: 2

Chandermani
Chandermani

Reputation: 42669

There were two issues with you code. Firstly you don't to alias the controller again, by using ng-controller in your template so that needs to be removed.

Secondly the controller is a function not object, so use:

this.age = '5';

Upvotes: 1

Related Questions