简体   繁体   English

如何从自定义指令中检索值并将其传递给控制器

[英]How to retrieve values from a custom directive and pass them to a controller

I have my main html file structured as follows: 我的主要html文件结构如下:

<html ng-app='information'>
<body ng-controller="FirstController as first>
<div ng-controller="SecondController as second>

Following is the custom directive. 以下是自定义指令。

<!-- Custom Directive -->

<div id="information">

    <myOwnDirective ng-controller="ThirdController as thirdCtrl"></myOwnDirective>

  </div>

Directive is created as follows: 指令创建如下:

(function() {

    var app = angular.module('information', ['ui.bootstrap']);

    app.directive('myOwnDirective', function(){
    return {
        restrict: 'E',
        templateUrl: 'my-own-directive.html',

        };  
    });

This is my custom directive template: 这是我的自定义指令模板:

<uib-accordion tag ng-repeat="info in first">

<form ng-submit="thirdCtrl.updateInformation()">

<div class="form-group">

<label for="someprop">Property</label> <input type="text" name="someprop"
            class="form-control" ng-model="info.propValue"
            ng-readonly="info.propValue">
 </div>

 <button type="submit" class="btn btn-success btn-lg btn-block">Click</button>
</form>

And here is my controller where there is the function that is to be invoked on ng-click in custom directive template. 这是我的控制器,这里有要在自定义指令模板中的ng-click上调用的函数。

(function() {
    angular.module('deviceInfo2').controller('FormController', [ '$scope','$http', function($scope) {               


        this.updateStatus =function () {

            console.log("Inside function");
        };
    }]);        
})();

I want to get data in my custom directive template on ng-click and pass it to the form controller but I cant seem to find way to get the data in there. 我想在ng-click上的自定义指令模板中获取数据,并将其传递给表单控制器,但是我似乎无法找到在其中获取数据的方法。 I have tried exploring creating a service but it is not working. 我尝试探索创建服务,但无法正常工作。 I think I am missing the scope. 我想我错过了范围。 Can anyone point me in the right direction please. 谁能指出我正确的方向。 I have been stuck on this for a while and need to make some progress. 我已经坚持了一段时间,需要取得一些进展。 Thank You. 谢谢。

If you find yourself creating a directive that produces an entire web form, you should question your approach. 如果您发现自己创建了一个可生成整个Web表单的指令,则应质疑您的方法。 Think smaller. 想小一点。 A directive that does too much is not very reusable and you will often find yourself in this situation. 太多的指令不是很可重用,并且您经常会遇到这种情况。

Instead of creating a directive that produces that entire web form, why not just create the web form as your view template? 除了创建可生成整个Web表单的指令之外,为什么不仅将Web表单创建为视图模板? Why even have a custom directive? 为什么还要有自定义指令?

If your answer is: "I want this web form to appear in multiple places within my app", consider using ng-include or ui-router to create a reusable state. 如果您的答案是:“我希望此Web表单出现在我的应用程序中的多个位置”,请考虑使用ng-includeui-router创建可重用状态。 A directive is a custom HTML element (or attribute), not a rubber stamp for huge chunks of code. 指令是自定义HTML元素(或属性),而不是用于处理大量代码的橡皮图章。

If you still need your custom directive to supply data to the parent directive, one good way to do it is to use the & data binding. 如果仍然需要自定义指令将数据提供给父指令,那么一种好方法是使用&数据绑定。

Working example: JSFiddle 工作示例: JSFiddle

JavaScript 的JavaScript

angular.module('myApp', [])
  .controller('MyController', MyController)
  .controller('MySelectController', MySelectController)
  .directive('mySelect', mySelectDirective)
;

function MyController() {
  var vm = this;
  vm.setValue = function(value) {
    vm.value = value;
  };
}

function MySelectController() {
  var vm = this;
  vm.items = [
    {label: 'One', value: 1},
    {label: 'Two', value: 2},
    {label: 'Three', value: 3}
  ];
}

function mySelectDirective() {
  return {
    bindToController: {
      callback: '&'
    },
    controller: 'MySelectController',
    controllerAs: 'vm',
    link: postLink,
    scope: true,
    template: '<select ng-model="vm.selected" ng-options="item.value as item.label for item in vm.items"></select>'
  };

  function postLink(scope, iElement, iAttrs, vm) {
    scope.$watch(function() {
      return vm.selected;
    }, function(newValue) {
      if (angular.isDefined(newValue) && typeof vm.callback === 'function') {
        vm.callback({$value: newValue});
      }
    });
  }
}

HTML 的HTML

<div ng-controller="MyController as vm">
  <my-select callback="vm.setValue($value)"></my-select>
  <p>Selected Value: {{vm.value}}</p>
</div>

If you have a scope variable in your controller scope, say 如果您的控制器范围中有一个范围变量,请说

$scope.var1 = '';

Make sure the controller's partial is where you use your custom directive. 确保控制器的局部位于使用自定义指令的位置。 Then in your directive's controller, you can use this below to push a value to the controller's scope: 然后,在指令的控制器中,可以在下面使用此命令将值推入控制器的作用域:

$scope.$parent.var1 = 'value to pass';

The assumption here is your directive has an isolated scope. 这里的假设是您的指令具有隔离范围。 Your controller's scope is the parent of your directive's scope, so you can use the $parent keyword to pass data. 控制器的作用域是指令作用域的父级,因此可以使用$parent关键字传递数据。

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

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