javascript - Passing a form to a directive: undefined -
i've got code (updated)
html
<body ng-controller="mainctrl"> <form name="form" novalidate> <directive form="form.test" required ><input type="text" ng-model="text" name="test" required="true" /></directive> <button ng-click="click()">click me</button> </form> </body> javascript
app.controller('mainctrl', function($scope) { $scope.click = function(){ console.log('click'); } }); app.directive('directive', function() { return { transclude: true, replace: true, scope: { form: '=', }, template: '<div>', link: function(scope, element, attrs, ctrl, transcludefn) { var inputdiv = angular.element('<div>') transcludefn(scope, function(clone){ inputdiv.append(clone); }) element.append(inputdiv); scope.$watch(function(){ return scope.form.$error; }, function(newvalue){ console.log('newvalue', newvalue); }, true) } } }); every time click on button error of form being undefined. try here: http://plnkr.co/edit/pl76wo4ajigh0m7b5nqd?p=preview
i see 2 things changed, first i'd add ng-model attribute text input , ng-required attribute error tracked model's controller
<input type="text" ng-model="test" ng-required="true" /> next need include objectequality parameter on $watch, watch changes on $error object properties
scope.$watch(function(scope) { return scope.form[scope.towatch].$error; }, function(newvalue) { // newvalue $error object input }, true); // notice last true value here, that's objectequality parameter here's updated plnkr: http://plnkr.co/edit/lnghwgzf5zbnqruxh4gp?p=preview
Comments
Post a Comment