dimanche 18 juin 2017

How can I pass a controller's scope property to a custom directive?

Basic Setup:

I have a modal form that has a custom directive as a child element inside of it. The custom directive is a button. The modal consists of an input checkbox as well.

The End Goal:

Whenever the checkbox is 'checked', the custom directive/button element should be enabled. If the checkbox is 'unchecked', the custom directive/button should be disabled.

When the checkbox is checked, the 'modalController' sets the $scope.isChecked value to true, when it's unchecked, $scope.isChecked is false.

I figured this can be achieved by using ng-checked on the button element. I would pass the value of isChecked to the custom directive where its value can be put in the ng-checked expression.

The Problem When I try this solution, the console log shows an error saying "inputCheck is not defined" Any ideas on how to make this work?

What I have so far AKA my thought process:

My thought process was to simply take the $scope.isChecked value from the modal controller, and pass that in to the Button Directive. I would pass that value to the button element in the custom directive:

Modal html:

  <div ng-controller= "modalController">
    <input type="checkbox" ng-model="isChecked">
    <button-directive inputCheck="isChecked"></button-directive>
  </div>

ButtonDirective.js:

angular.module('starter').directive('buttonDirective', function ($uibModal) {
    return {
        restrict: "EA",
        templateUrl: "app/directives/button-directive.html",
        scope: {
          inputCheck: "@"    
        },
        controller: ['$scope', function ($scope) { 
                  console.log(inputCheck);
         }]
     };
});

button-directive.html:

<button ng-checked="inputCheck">




Aucun commentaire:

Enregistrer un commentaire