And*_*nço 10 angularjs angularjs-directive
我有一个输入元素,我想使用自定义指令绑定ngModel和ngClass,但我遇到了一些麻烦.
是)我有的:
<input type="text" myDirective="PropertyFromScope" />
Run Code Online (Sandbox Code Playgroud)
我想要的结果是:
<input type="text" ng-model="PropertyFromScope" ng-class="{'class' : MethodFromScope}" />
Run Code Online (Sandbox Code Playgroud)
我试图避免使用模板,因为我希望该指令适用于任何输入标记.
这是我到目前为止所得到的:
angular.module('customDirectives', [])
.directive('myDirective', function () {
var linker = function (scope, element, attrs) {
attrs.$set('ngModel', attrs.myDirective);
attrs.$set('ngClass', '{\'class\' : MethodFromScope}');
}
return {
restrict: 'A',
link: linker
}
});
Run Code Online (Sandbox Code Playgroud)
这是一个JSFiddle:http://jsfiddle.net/Q8QJJ/
Nix*_*Nix 12
你想要做到这一点吗?
很简单的解决方案
myApp.directive('myDirective', function ($compile) {
return {
restrict: 'A',
compile: function(element, attrs) {
element.attr('ng-model', attrs.myDirective);
element.removeAttr("my-directive");
element.attr('ng-class', '{\'class\' : testFunction()}');
return {
pre: function preLink(scope, iElement, iAttrs, controller) { },
post: function postLink(scope, iElement, iAttrs, controller) {
$compile(iElement)(scope);
}
}
}
}
});
Run Code Online (Sandbox Code Playgroud)
这是一个小提琴http://jsfiddle.net/V9e9M/
| 归档时间: |
|
| 查看次数: |
8418 次 |
| 最近记录: |