简体   繁体   English

角度指令更新父控制器对象

[英]Angular Directive updating Parent Controller Object

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. 我已经使用Angular一段时间了,但是当涉及到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. 我的控制器FormCtrl从应用程序缓存中加载了一些数据。 It then passes this data to an object called ctrl.form_fields. 然后,它将这些数据传递到名为ctrl.form_fields的对象。

I need my directive to be able to access ctrl.form_fields to display the data. 我需要我的指令才能访问ctrl.form_fields以显示数据。 Additionally, if any change to the data is made within the directive the FromCtrl ctrl.form_fields object is updated. 此外,如果在指令中对数据进行了任何更改,则将更新FromCtrl ctrl.form_fields对象。

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. 我不想使用$ scope。$ parent等...来完成此操作,因为它将变得太凌乱且难以维护。 Plus I'm trying not the use $scope as much as possible. 另外,我尝试不尽可能多地使用$ scope。

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'. 然后,在您的控制器中,可以使用参考“ vm.fields”。 Your input field should be: 您的输入字段应为:

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

I haven't tested this though. 我还没有测试过。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM