0

I've been using Angular for a while but I'm a little lost when it comes to two-way data binding between a Controller (which is using the controller as syntax) and a directive which is inside the template for that controller.

The purpose of the directive is to essentially be an input field for a very specific set of data I need to collect (photograph, text and a few other things).

How it works.

My controller FormCtrl loads in some data from app cache. It then passes this data to an object called ctrl.form_fields.

I need my directive to be able to access ctrl.form_fields to display the data. Additionally, if any change to the data is made within the directive the FromCtrl ctrl.form_fields object is updated.

I've done some research and experimentation on two-way binding between a parent controller and child directive but I can't figure it out. If someone could post up a theoretical example I'd really appreciate it.

I don't want to use $scope.$parent etc... to accomplish this as it will get too messy and difficult to maintain. Plus I'm trying not the use $scope as much as possible.

Cheers, Dean

2 Answers 2

1

Maybe I didn't understand your question correctly, but cant you pass the object/value to the directive through attributes, and use a two-way binding expression?

angular
  .module('app')
  .directive('myDirective', function() {
    return {
     restrict: 'E',
     templateUrl: 'myTemplate.html',
     scope: {
       obj: "=" // Two way decleration  
     },
      
     controller: function($scope) {
       console.log($scope.obj); 
     }
   }
  });
<my-directive obj="ctrl.object"></my-directive>

angular

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. This worked. I just couldn't get my head around two way binding in this instance. I was missing the '=' declaration. :) One question though - in my directive, the Contollers variable is now available but only on $scope. Is there any way I can pass it in so I'm not using $scope.data ?
0

An example of the (part of the) directive:

controller: FooController, // import FooController as './foo.controller';
controllerAs: 'vm',
replace: true,
scope: {
  fields: '=formFields'
},
template: '<input type="text" ng-model="fields" />'

Then in your controller, you can use the reference 'vm.fields'. Your input field should be:

<input type="text" form-fields="fields" />

I haven't tested this though.

Comments

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.