How to add ng-model functionality to a component

匿名 (未验证) 提交于 2019-12-03 08:30:34

问题:

Angular ng-change on ng-model passed into child directive

Basically, I want to be able to pass in ng-model from a parent directive to a child directive. I could just in a 2-way binded value, but then I wouldn't be able to use a ng-change in the parent directive on the child element. I could also use ng-click, but this wouldn't work with a non-clicking change (such as a text area instead of a checkbox). So I'm wondering if there's a way to allow a custom directives to have a ng-model/ng-change pair similar to how inputs, buttons, text areas and other html elements can. I want to avoid using emits, ons, watches, passing callbacks, etc. I just want to be able to do [input type="checkbox" ng-model="ngModel"] on a custom directive instead of input.

Parent Template

Parent Directive

$scope.x = function() {console.log('hi')};

Child Template

Child Directive ??

$scope.ngModel = $element.controller('ngModel'); 

My angular version is 1.4.8 btw.

Thanks :)

回答1:

Almost the same as @georgeawg answer, but using directive method (since component was introduced in 1.5+, but author has 1.4.8):

angular.module('myApp', []) .controller('MyCtrl', ['$scope', function MyCtrl($scope) {  }]) .directive('inputComponent', [function () {         var myDirective = {             restrict: 'E',             require: 'ngModel',             templateUrl: "checkboxComponent.html",             link : function(scope, element, attrs, ngModelCtrl){                 scope.updateModel = function(ngModel) {                     ngModelCtrl.$setViewValue(ngModel);                 }             }         }         return myDirective; }]);
fieldset {   margin-top: 1em; }

value = {{value}}

value2 = {{value2}}



回答2:

How to add ng-model functionality to a component

Use one-way input for input and use the ngModelController API for output:

app.component("checkboxComponent", {     bindings: { ngModel: '     `,     controller: function() {       this.ngModelChange = () => {         this.ngModelCtrl.$setViewValue(this.ngModel);       };     } })

The component uses one-way binding for input, and $setViewValue for output. With this method, the ng-change works, and the component can be used as a form element:

For more information, see

The DEMO

angular.module("app",[])  .component("checkboxComponent", {     bindings: { ngModel: '           

Checkbox Component

Checkbox `, controller: function() { this.ngModelChange = () => { this.ngModelCtrl.$setViewValue(this.ngModel); }; } })

value = {{value}}

value2 = {{value2}}



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!