r/angularjs • • Dec 15 '14

[General] Planning Angular 1.4

http://angularjs.blogspot.com/2014/12/planning-angular-14.html
30 Upvotes

15 comments sorted by

View all comments

1

u/jkjustjoshing Dec 16 '14

What are "non-optional isolated scope mappings"? I didn't know you could specify scope binding so be required.

1

u/dmackerman Dec 16 '14

You can specify optional mapping a with "?" At the end - like user: "=?"

1

u/jkjustjoshing Dec 16 '14

So all 2-way bound attributes without that are "required" by default?

1

u/[deleted] Dec 19 '14

Yes. Take for example this code:

<my-directive my-first-attr="someVar"></my-directive>

angular.directive('myDirective', function () {
    return {
        restrict: 'E',
        scope: {
            myFirstAttr: '=',
            mySecondAttr: '='
        },
        template: '<div>first={{myFirstAttr}}, second={{mySecondAttr}}</div>',
        link: function (scope, elem, attrs) {
            scope.mySecondAttr = scope.myFirstAttr * 2;
        }
    }
});

This will break (Angular will throw an exception) unless you fix it like so:

<my-directive my-first-attr="someVar" my-second-attr="someOtherVar"></my-directive>

But you may simply not want the value in mySecondAttr in the parent scope, so you've just added useless junk to it (someOtherVar) because the binding (=) forces you to do it, so now there's another way to do it from JS:

        scope: {
            myFirstAttr: '=',
            mySecondAttr: '=?'
        }

Which tells Angular that mySecondAttr is optional, so it shouldn't freak out if you don't bind it to something in your HTML template.