farzad farzad - 19 days ago 5x
AngularJS Question

How use controller variable inside a AngularJs directive

How use controller variable inside a directive . I used popoverHtml inside scope in directive but when i add type like this type not work :

like this : scope: { popoverHtml:'@', type: @ },

my html is :

good <input type='radio' name='type' value='good' data-ng-model='type'
data-ng-change='change(type)' />
bad <input type='radio' name='type' value='bad' data-ng-model='type'
data-ng-change='change(type)' />
<next-level id='pop' popover-html='{{typeMessage}}'></next-level>

my controller is :

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
$scope.typeMessage = 'PopOverTest';
$scope.type = false;
$scope.change = function(type){
if(type == 'good'){
$scope.typeMessage = 'very good';
}else if(type == 'bad'){
$scope.typeMessage = 'very bad';

my directive :

app.directive('nextLevel', function () {
return {
restrict: 'EA',
scope:{ popoverHtml:'@'},
template: '<a ui-sref="register" tabindex="0" linkdisabled="{{type}}"
class="btn btn-block btn-success ng-class: {disabled: !(type)}" role="button" >next</a>',
link: function (scope, el, attrs){
trigger: 'click',
html: true,
title: 'notice !!',
content: scope.popoverHtml, // Access the popoverHtml html
placement: 'bottom'

attrs.$observe('popoverHtml', function(val){
var popover = $(el[0]).data('bs.popover');
popover.options.content = val;


demo : https://plnkr.co/edit/wfC4DrTIp8fRIs6hEEDa?p=preview


You cannot send type as @ binding to the directive, if you want to use it inside ng-class. If you do changes to type in main controller, they will not be reflected in ng-class inside the directive. Take look here.

In order to reflect changes in ng-class you have to pass it as an = binding.

Plunker here