Angular Js Directive, Change A 2 Way Data Binding In The Link Function
I'm trying to create an angular directive where I can set the options either via a single options object, or via some attributes.  Here is an example of the kind of code: app.direc
Solution 1:
If you don't pass the two way data binding, angular gets angry:
https://github.com/angular/angular.js/issues/1435
Use optional binding (=?):
app.directive('testElement', [function () {
    return {
        restrict: "E",
        scope: {
            options: "=?"
        },
        template: "<p><span>Name: </span>{{ options.name }}{{ test }}</p>",
        link: function (scope, element, attrs) {
            scope.options = scope.options || {};
            if (attrs.name)
                scope.options.name = attrs.name;
        }
    };
}]);
Or if you are using an older version of angular, use $eval on attrs. options:
app.directive('testElement', [function () {
    return {
        restrict: "E",
        //Still can create isolate scope to not clobber parent scope variables.
        scope: {},
        template: "<p><span>Name: </span>{{ options.name }}{{ test }}</p>",
        link: function (scope, element, attrs) {
            scope.options = scope.$eval(attrs.options) || {};
            if (attrs.name)
                scope.options.name = attrs.name;
        }
    };
}]);
Solution 2:
The directive requires a options parameter. In second case you have not supplied it and hence there is an error
If the isolated scope variable is optional use ? like
 scope: {
            options: "=?"
        }
See my plunkr http://plnkr.co/edit/eGh6r1X7HzY1sZIDYZ69?p=preview
and documentation on isolated scope here http://docs.angularjs.org/api/ng/service/$compile
Post a Comment for "Angular Js Directive, Change A 2 Way Data Binding In The Link Function"