How to use ngChange in a custom directive

I want to create a directive for the toggle button, I have a code that I want to enter into the directive:

<div class="toggle-button" ng-class="{true: toggleTrue === true, false: toggleTrue === false}">
    <button class="true" ng-click="toggleTrue = true">Y</button><button class="false" ng-click="toggleTrue = false">N</button>
</div>

(I only work with style changes, so I only have a class change)

I want to have something like:

<toogle ng-change="SomeFunction()" ng-model="someValue" />

How can I work with ng-change in my directive? Should I just parse attr or use the scope attribute or is there code similar to ngModel that needs to be used with ngChange.

+4
source share
2 answers

On trying and error, I found code that works with ngModel and ngChange:

return {
    restrict: 'E',
    require: 'ngModel',
    scope: {},
    template: '<div class="toggle-button" ng-class="{true: toggleValue === true, false: toggleValue === false}">'+
        '<button class="true" ng-click="toggle(true)">Y</button>'+
        '<button class="false" ng-click="toggle(false)">N</button>'+
        '</div>',
    link: function(scope, element, attrs, ngModel) {
        ngModel.$viewChangeListeners.push(function() {
            scope.$eval(attrs.ngChange);
        });
        ngModel.$render = function() {
            scope.toggleValue = ngModel.$modelValue;
        };
        scope.toggle = function(toggle) {
            scope.toggleValue = toggle;
            ngModel.$setViewValue(toggle);
        };
    }
};

scope: true ( $scope.toggle, , )

+5

:

:

$scope.someFunction = function(){...};
$scope.someValue = false;

:

<toggle change="someFunction" value="someValue"/>

( , someValue boolean true/false):

app.directive('toggle', function(){
    return{
        restrict: 'E',
        replace: true,
        template: ''+ 
            '<div class="toggle-button" ng-class="toggleValue">'+
                '<button ng-class="toggleValue" ng-click="change()">{{toggleValue&&\'Y\'||\'N\'}}</button>'+
            '</div>',
        scope: {
            toggleValue: '=value',
            toggleChange: '=change'
        },
        link: function(scope){
            scope.change = function(){
                scope.toggleValue = !scope.toggleValue;
                scope.toggleChange();
            }
        }
    };
})
+1

Source: https://habr.com/ru/post/1545074/


All Articles