0

Why color: "@" work but color: "=" not work in the below code?

http://jsfiddle.net/edwardtanguay/pz2L6etv/8/

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

function mainController($scope) {
    $scope.message = 'alsjkf';
}

myApp.directive('uiCalendar', function () {
    return {
        restrict: 'A',
        scope: {
            message: "@theMessage",
            color: "=" //works with @
        },
        link: function (scope, element, attrs) {
            scope.color = scope.color === undefined ? 'black' : scope.color;
            $(element).append('<p style="color:'+scope.color+'">added this2: ' + scope.message + ' (' + scope.color + ')</p>');
        }
    };
});
Edward Tanguay
  • 189,012
  • 314
  • 712
  • 1,047

2 Answers2

2

The reason is that = is used to bind to variable in parent scope contained within the attribute value

Your color values are not scope variables in the parent scope(controller), they are only strings in your use case. There is no $scope.green or $scope.blue in controller to bind to.

The = would work if you did:

function mainController($scope) {
    $scope.message = 'alsjkf';
    $scope.blue ='#0B0EFF';
}

Then the hex value would be used inside scope of directive.

@ will just take the string value and pass it to directive scope

charlietfl
  • 170,828
  • 13
  • 121
  • 150
  • Great, thanks, I got this working where the directive changes the values in the parent scope, if anyone is looking for an example: http://jsfiddle.net/edwardtanguay/pz2L6etv/14/ – Edward Tanguay Aug 13 '15 at 10:00
0

Directive bindings have different approaches to how they are interpreted.

Using @ means that the scope variable is bound to the string literal value that is passed as that attribute. So using color: '@' binds the scope variable color to the exact value of color="green", which would be scope.color == "green" // this evaluates to true

Using = binds the scope variable to the evaluation of the expression passed in the attribute. You can use string expressions to get literals, like color: "=" and then have <span color="'green'"></span>

Using & binds the scope variable to the function that is passed in the attribute. Doing something like click: '&' and then <span click="clickMe()"></span> will make scope.click() fire off clickMe().

This question has some more info and links to other resources that go into more detail.

Community
  • 1
  • 1
Joe Pontani
  • 451
  • 4
  • 13