我试图用角度编写一个简单的自定义指令,将标记转换为切换按钮(类似于复选框)。到目前为止,我编写的代码更新了内部变量(孤立的作用域),但是双向绑定似乎不起作用。当我单击该按钮时,按钮会切换( css类出现并消失),但myVariable没有更新。
任何帮助都非常感谢!
用法
<button toggle-button="myVariable">My Button</button>指令码
( function() {
var directive = function () {
return {
restrict: 'A',
scope: {
toggleButton: '=checked'
},
link: function( $scope, element, attrs ) {
$scope.$watch('checked', function(newVal, oldVal) {
newVal ? element.addClass ('on') : element.removeClass('on');
});
element.bind('click', function() {
$scope.checked = !$scope.checked;
$scope.$apply();
});
}
};
};
angular.module('myApp')
.directive('toggleButton', directive );
}());发布于 2015-04-25 20:07:48
只需替换
scope: {
toggleButton: '=checked'
}至
scope: {
checked: '=toggleButton'
}发布于 2015-04-25 19:55:01
您的指令范围是寻找一个不存在的属性。
试着改变:
scope: {
toggleButton: '=checked'
},至
scope: {
toggleButton: '='
},区别在于=checked将查找属性checked,而=将使用与作用域对象中的属性名称相同的属性。
也需要更改$watch,但是可以去掉它并使用ng-class。
发布于 2015-04-25 20:13:02
正如charlietfl所说,您不需要这个检查变量。您正在对它进行更改,而不是外部变量。
以下是一个固定的版本:
angular.module('components', [])
.directive('toggleButton', function () {
return {
restrict: 'A',
scope:{
toggleButton:'='
},
link: function($scope, $element, $attrs) {
$scope.$watch('toggleButton', function(newVal) {
newVal ? $element.addClass ('on') : $element.removeClass('on');
});
$element.bind('click', function() {
$scope.toggleButton = !$scope.toggleButton;
$scope.$apply();
});
}
}
})
angular.module('HelloApp', ['components'])http://jsfiddle.net/b3b3qkug/1/
https://stackoverflow.com/questions/29869941
复制相似问题