Akira Hojo
Akira Hojo

Reputation: 13

AngularJS : pass ng-model from directive component to controller

Inspired by angular ui, I want to create front-end library as a pieces of component, all as an angularjs directive. So that the user can simply put directive with some configurations and get the desire result of component.

So this is how the directive will look like.

<date-picker 
    date-format="MM.DD.YYYY HH:mm" 
    enable-navigation 
    date-picker-id="datetimepicker2"
    date-picker-model="myModel1">
</date-picker>

For the usage, the idea is that it could be wrapped by user-created controller and the controller can reach the directive scope like this.

<div ng-controller="myController">
   <date-picker 
         ...
       date-picker-model="myModel1">
   </date-picker>
</div>

(The reason I use component-name-model is because the component directive template might have more than one model) And the code in controller would be

angular.module('myApp').controller('myController',['$scope', function($scope) {
     $scope.myModel1; //this scope binds to the datepicker template scope 
}]);

Since I'm pretty new to angularJs, my questions are follow.

  1. How to make the controller reach the directive scope with this syntax ? In my case, It seems that the controller didn't notice about directive scope (see my code in plunker)

  2. Right now I'm also stuck with passing model to the template. as you can see in directive I've define date-picker-model="myModel1" and then directive will catch attrs and pass it to template like this

    if('datePickerModel' in attrs){
         $scope.datePickerModel = attrs.datePickerModel;
    }
    

    and when I'm using expression on templateUrl, ng-model="{{datePickerModel}}" doesn't work

The code is quite long so I would suggest you the check out my plunker

Thank you :-)

Upvotes: 1

Views: 1612

Answers (1)

stetro
stetro

Reputation: 547

take a look at the scope parameter by creating your directive. There you can assign your 2-way binding between the controller and the directive's scope.

http://plnkr.co/edit/ngdoc:example-example85@snapshot?p=preview

<my-customer info="igor"></my-customer>


angular.module('docsIsolateScopeDirective', [])
.controller('Controller', ['$scope', function($scope) {
  $scope.naomi = { name: 'Naomi', address: '1600 Amphitheatre' };
  $scope.igor = { name: 'Igor', address: '123 Somewhere' };
}])
.directive('myCustomer', function() {
  return {
    restrict: 'E',
    scope: {
      customerInfo: '=info'
    },
    templateUrl: 'my-customer-iso.html'
  };
});

also documented here: http://docs.angularjs.org/guide/directive

be also aware of the beginning symbol '=' or '@'!

Upvotes: 0

Related Questions