keldar
keldar

Reputation: 6242

Passing a $scope variable to a directive

I am struggling to pass data from my model to a directive and have little to no idea how. I am an AngularJS newbie :).

My markup is as follows below. Currently witnessing two problems:

1) scope.$parent.companyName is always blank no matter what I type? I have declared an empty value because otherwise it's undefined and that seems like an anti-pattern.

2) Even if I get (1) working, it's relying on the layout of the model I give it because of $parent. How do I pass a string to the directive?

I have a view:

<ion-view>
    <ion-header-bar class="bar-royal">
        <h1 class="title">{{ registerTitle }}</h1>
    </ion-header-bar>
    <ion-content>
        <div class="list list-inset">
            <label>
                {{ registerInfoLabel }}
            </label>
            <label class="item item-input">
                <input type="text" placeholder="{{ companyNameLabel }}" ng-model="companyName">
            </label>
            <label>
                <button class="button button-block button-royal" register-app>
                    {{ registerLabel }}
                </button>
            </label>
        </div>
    </ion-content>
</ion-view>

A controller:

angular.module('app')

    .controller('RegisterController', ['$scope', '$appI18n', function ($scope, $appI18n) {
        $scope.registerTitle = $appI18n.RegisterTitle;
        $scope.registerLabel = $appI18n.RegisterLabel;
        $scope.companyNameLabel = $appI18n.CompanyName;
        $scope.registerInfoLabel = $appI18n.RegisterInfoLabel;

        $scope.companyName = '';
    }]);

And a directive:

angular.module('app')

    .directive('registerApp', ['RegisterService', function (RegisterService) {
        return {
            restrict: 'AE',
            link: function (scope, element, attrs) {
                element.bind('click', function () {
                    alert(scope.$parent.companyName);
                })
            }
        }
    }]);

Upvotes: 0

Views: 1017

Answers (1)

KayakDave
KayakDave

Reputation: 24676

You can send a string in to the directive using an attribute. If you only have one parameter to send then you can use the directive itself like this:

<div register-app="companyName"></div>

And adding it to your directive scope:

scope: { registerApp : '=' },

Then it'll be available on your scope:

link: function (scope, element, attrs) {
      console.log("cname ",scope.registerApp);
}

Here's an example of that working: http://jsfiddle.net/kgwkf02c/

Or you could send it in using it's own attribute (especially useful if you want to send in multiple values):

<div register-app cname="companyName"></div>

With the directive looking like:

scope: { cname : '=' },
link: function (scope, element, attrs) {
          console.log("cname ",scope.cname);
}

Here's that version: http://jsfiddle.net/kgwkf02c/1/

Upvotes: 1

Related Questions