简体   繁体   中英

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

I have my main html file structured as follows:

<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.

(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. 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. 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? 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. A directive is a custom HTML element (or attribute), not a rubber stamp for huge chunks of code.

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

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

<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.

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.

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