r/angularjs • • Feb 16 '15

Example of use of parse in AngularJs Directive - Jose Mendez blog

http://www.jomendez.com/2015/02/10/example-parse-angularjs-directive/#J23R
2 Upvotes

6 comments sorted by

5

u/rq60 Feb 16 '15

No offense, but this is jQuery spaghetti wrapped in a directive.

1

u/jomendez Feb 16 '15

That's what a directive is for, to wrap the DOM manipulation, which is easier with Jquery, Now, I'm agree with you, it is spaghetti code, I admit that I could organize a little bit more the code, creating some functions to wrap up the code, etc, There is always a way to do it better. But for the purpose of this post, which is show an example of $parse service in AngularJS, this code is good enough, I respectfully encourage you to do it better, and share your solution with the community :)

2

u/rq60 Feb 16 '15

Okay, how about something like this?

.directive("editInPlace", function() {
        return {
            restrict: 'A',
            scope: true,
            template: [
                '<div ng-switch="edit.editing">',
                    '<div ng-switch-when="true">',
                        '<input type="text" ng-model="edit.value" />',
                        '<button ng-click="edit.toggleEdit()">Done</button>',
                    '</div>',
                    '<span ng-switch-default ng-click="edit.toggleEdit()">{{ edit.value }}</span>',
                '</div>'
            ].join(""),
            controller: function($scope, $attrs) {
                var edit = this;
                edit.editing = false;
                edit.value = $scope.$eval($attrs.editInPlace);
                edit.toggleEdit = function() {
                    edit.editing = !edit.editing;
                    $scope.$eval([$attrs.editInPlace , "=", JSON.stringify(edit.value)].join(""));
                };
            },
            controllerAs: "edit"
        };
    });

edit - here it is dropped in to your code example: http://jsfiddle.net/ks5et82p/23/

1

u/chazzlabs Feb 17 '15

To be fair, the point of OP's example was to show off Angular's $parse service, which you didn't do in your example.

3

u/rq60 Feb 17 '15

Because there was no need. $scope.$eval is:

$eval: function(expr, locals) {
    return $parse(expr)(this, locals);
  },

where this is the $scope.