0

I want to use one way data binding from controller to my directive, but I get undefined instead of real value.

Here is definition of directive scope

scope: {
    eventAdmin: '@',
    eventId: '@'
  }

Here is how I use directive.

<directive event-admin="{{eventAdmin}}" event-id="{{eventId}}"></directive>

And here is my link function

function directiveLink (scope, element, attrs) {
console.log(scope.eventId); //-> undefined

}

6
  • 1
    <directive event-admin="eventAdmin" event-id="eventId"></directive> Commented Jul 17, 2016 at 17:34
  • please post the complete directive code Commented Jul 17, 2016 at 18:03
  • trying consoling variable before the directive and see what that returns Commented Jul 17, 2016 at 18:06
  • Your code should work. Do you have an example of it not working? Commented Jul 17, 2016 at 18:11
  • 1
    @SamiTriki The OP is not asking for that. The OP is correctly binding to the value of the elements attribute. It's just that the value in initialized by the "parent" scope variable. This is what makes it "one way" binding. Commented Jul 17, 2016 at 18:16

1 Answer 1

1

If the directive's name is "directive" and the containing controller's scope has the properties "eventAdmin" and "eventId" then this should be working.

I made a JSFiddle of your example: https://jsfiddle.net/Royar/qu55ujj5/4/

HTML:

<div ng-app="myApp" ng-controller="myCtrl">
  <directive event-admin="{{eventAdmin}}" event-id="{{eventId}}"></directive>
</div>

JS:

var myApp = angular.module('myApp', []);
angular.module("myApp").controller("myCtrl", function($scope) {
  $scope.eventAdmin = "aaa";
  $scope.eventId = "bbb";

});
angular.module("myApp").directive("directive", function() {
  return {
    scope: {
      eventAdmin: "@",
      eventId: "@"
    },
    template: "{{eventAdmin}}",
    link: function(scope, element, attrs) {
      console.log(scope.eventAdmin); //working
    }
  };
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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