AngularJS Custom Directive Two Way Binding

前端 未结 5 1060
甜味超标
甜味超标 2020-12-29 08:17

If I have an AngularJS directive without a template and I want it to set a property on the current scope, what is the best way to do it?

For example, a directive tha

5条回答
  •  無奈伤痛
    2020-12-29 08:49

    You can definitely simplify it a bit like this without using $parse

    angular.module('directive-binding', []).directive('twoway', [function () {
        return {
            scope: false,
            link: function (scope, elem, attrs) {
                elem.on('click', function () {
                    scope[attrs.twoway] = scope[attrs.twoway] == null ? 1 : scope[attrs.twoway] + 1;
                    scope.$apply();
                });
            }
        };
    }]);
    

提交回复
热议问题