AngularJS - ng-change as an option in a custom directive

假装没事ソ 提交于 2019-12-11 02:34:13

问题


I want to add an ng-change function into a custom directive but I'm not sure if ng-change will go inside the template or into link function, additionally I'd like to make the ng-change optional (calling '

<text-edit-in-place value="loan.due_date" change="checkException" param="foobar">

' would add the checkException('foobar') function where leaving out change= & param= would not run any ng-change).

function TextEditInPlaceDirective() {
    return {
        restrict: 'E',
        scope: {
            value: '='
        },
        template: '<span ng-click="edit()" ng-show="!editing">{{ value}}</span><input ng-model="value" ng-blur="onBlur()" ng-show="editing"></input>',
        link: function($scope, element, attrs) {
            var inputElement = element.find('input');

            // reference the input element
            element.addClass('edit-in-place');

            // Initially, we're not editing.
            $scope.editing = false;

            // ng-click handler to activate edit-in-place
            $scope.edit = function() {
                $scope.editing = true;

                // element not visible until digest complete
                // timeout causes this to run after digest
                setTimeout(function() {
                    inputElement[0].focus();
                });
            };

            $scope.onBlur = function() {
                $scope.editing = false;
            };
        }
    };
}

Help would appreciated, Thanks.


回答1:


You should be able to use a format similar to This fiddle

In that format, you can define the function within the directive, then specify whether or not you want the function to be called.

Example:

<test-change value="blah" check-exceptions="true" ng-model="foo"/>

That should be the most straight-forward way to do it.

Then you can define the function within the link function in the directive.



来源:https://stackoverflow.com/questions/28516256/angularjs-ng-change-as-an-option-in-a-custom-directive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!