2013-08-21 37 views
3

HTML:AngularJS:错误:没有控制器:形式

<div ng-app="my-app" ng-controller="AppController"> 
    <ng-form name="myform"> 
     <gtux-el></gtux-el> 
    </ng-form> 
</div> 

JS

var app = angular.module('my-app', [], function() { 
}) 

app.controller('AppController', function ($scope) { 
}) 

app.directive('gtInputMsg', ['$compile', '$interpolate', '$log', function($compile, $interpolate, $log) { 
    function link($scope, element, attrs, ctrls) { 
     var modelCtrl = ctrls[0], formCtrl = ctrls[1], msgCtrl = ctrls[2]; 

     element.on('click', function() { 
      console.log('gt-input-msg:click', element) 
     }); 
    }; 

    return { 
     require : ['ngModel', '^form', 'gtInputMsg'], 
     link : link 
    }; 
}]); 

app.directive('gtuxTextfield', ['$compile', '$timeout', '$log', function($compile, $timeout, $log) { 
    return { 
     restrict : 'E', 
     template : '<input type="text" name="field" gt-input-msg ng-model="fieldvalue" />', 
     replace : true 
    }; 
}]); 

app.directive('gtuxEl', ['$compile', '$timeout', '$log', function($compile, $timeout, $log) { 
    function link($scope, $element, attrs, ctrl) { 
     //here compile is used because in my use case different elements are used based on some option values. A service provides the template to be used based on a key 
     var $cr = $compile('<gtux-textfield></gtux-textfield>')($scope); 
     $($cr).appendTo($element); 
    } 

    return { 
     restrict : 'E', 
     link : link, 
     transclude : true 
    }; 
}]); 

错误

Error: No controller: form 
    at Error (<anonymous>) 
    at getControllers (http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js:4278:19) 
    at http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js:4284:24 

演示:Fiddle

据我可以看到有一个ng-form elemen t位于层次结构的顶部,应该提供从控制器到gtInputMsg指令。

这怎么解决?

+1

问题是,您没有页面上的“form”元素。 'ng-form'意味着被隐式使用。 – finishingmove

回答

4

您正在编译<gtux-textfield>元素,因为您尚未将它添加到DOM中的表单之下。试试:

var $cr = $('<gtux-textfield></gtux-textfield>').appendTo($element); 
$compile($cr)($scope); 

在你的gtuxEl链接功能。

演示:Fiddle

相关问题