首页 > 代码库 > [AngularJS] Using ngModel in Custom Directives
[AngularJS] Using ngModel in Custom Directives
You can use ngModel in your own directives, but there are a few things you‘ll need to do to get it working properly.
ngModel itself is an directive. If you want to use it inside your own directive, you should use require keyword.
/** * Created by Answer1215 on 12/18/2014. */angular.module(‘app‘, []) .directive(‘bank‘, function() { return{ restrict: ‘E‘, template: ‘<div>Click me to add $10 into your account</div>‘, require: ‘ngModel‘, //The ^ prefix means that this directive searches for the controller on its parents (without the ^ prefix, the directive would look for the controller on just its own element) link: function(scope, element, attrs, ngModelCtrl) { //so it looks for the controller on ngModel --> ngModelController //it has method setViewValue //has prop: viewValue element.on(‘click‘, function() { ngModelCtrl.$setViewValue(ngModelCtrl.$viewValue + 10); scope.$apply(); }) } } })
<!DOCTYPE html><html ng-app="app"><head lang="en"> <meta charset="UTF-8"> <title></title></head><body><div ng-init="money=10"></div><bank ng-model="money"></bank>{{money | currency}}<script src="bower_components/angular/angular.min.js"></script><script src="app.js"></script></body></html>
[AngularJS] Using ngModel in Custom Directives
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。