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
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
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.