user4266661
user4266661

Reputation:

AngularJS Directive: Get Object from Attribute

I'm creating a directive which generates some markup based on a property of an associated field. I plan on using it like this:

 <mvc-error-list field="myForm.testField"></mvc-error-list>

Within the directive I want to look up a property of the myForm.testField object. But I'm unclear on how to retrieve the myForm.testField object based on the string value being passed in to the template function.

Upvotes: 0

Views: 391

Answers (1)

Nicholas Thomson
Nicholas Thomson

Reputation: 548

If you want to share an object between your controller and your directive you can use an isolate directive scope and two-way bind a property on your directive's scope to one on your controller's scope.

angular.module('testApp', [])
.directive('myDirective', function(){
  return {
    restrict: 'E',
    scope: {
      field: '='
    },
    link: function(scope){
      console.log(scope.field.message)
    }
  };
})
.controller('myCtrl', function($scope){
  $scope.ctrlField = { message: 'Hello, World' };
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app='testApp' ng-controller='myCtrl'>
  <my-directive field='ctrlField'></my-directive>
</div>

Alternatively, if you don't need to pass anything back to your controller you can use a one-way binding. Which works the same way, but you use the & symbol instead of = when defining your isolate scope. You also need to access the property as a function, as a one-way databind creates a "getter function" on your directive's scope.

Upvotes: 0

Related Questions