如何在custom指令中使用ngChange

时间:2014-06-18 13:05:06

标签: javascript angularjs angularjs-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>

(我只参与风格改变,这就是为什么我只改变课程)

我希望有类似的东西:

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

我如何在指令中使用ng-change?我应该只解析attr还是使用scope属性,还是像ngModel这样的代码需要与ngChange一起使用。

2 个答案:

答案 0 :(得分:5)

通过尝试和错误,我找到了与ngModel和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变量用作模型,它会尝试执行该布尔值而不是函数)

答案 1 :(得分:1)

尝试这种方式:

控制器:

$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();
            }
        }
    };
})