1

我有动态创建输入标签的指令。我需要在更改事件中获取已创建输入的值。取而代之的是,参数中的name属性是未定义的。如何在指令控制器中获得价值?$scopecontrollerng-model

module.directive('createControl', function($compile, $timeout){
   return {           
     transclude: true,
     restrict: 'A',   
     scope: {         
       name: '=name'
     },
     link: function(scope, element, attrs){
         // simplified version
         tag = '<input type="text" ng-model="name"/>'
         element.append(html);
     controller: function($scope){
         // In the controller I need to get value of created input on change event
         console.log($scope);
     }
   }
});
4

2 回答 2

2

我不是 100% 确定你想做什么,但我猜它是这样的:

module.directive('createControl', function($compile, $timeout){
   return {   
     transclude: true,
     restrict: 'A',   
     scope: {         
       name: '=name'
     },
     link: function(scope, element, attrs){
         // simplified version
         var tag = angular.element('<input type="text" ng-model="name" ng-change="changed(name)">');
         element.append(tag);
         $compile(tag)(scope);
     },
     controller: function($scope){
         // In the controller I need to get value of created input on change event
         $scope.changed=function(name){
           console.log('changed to: '+name);
         }
     }
   }
});

链接函数创建一个新的输入元素,将其与$compile服务一起编译,然后将新的输入元素与scope. 这适用于以下标记:

Hello {{myInput}}!
<div create-control name="myInput">  
</div>

看看这个 plunker:http ://plnkr.co/edit/7XY90LXNn6gqpP47JaCH?p=preview

于 2013-05-09T09:12:21.620 回答
1

问题controller早于directive. 所以在控制器中应该是$watched $scope,而不是在directive. 但是我认为controller绑定到 adirective不应该知道directive状态,如果我错了,请纠正我。

所以有两种方法:

module.directive('createControl', function($compile, $timeout){
   return {   
     transclude: true,
     restrict: 'A',   
     scope: {         
        name: '=name'
     },
     link: function($scope, $element, $attrs){
         // simplified version
         var tag = angular.element('<input type="text" ng-model="name" ng-change="changed(name)">');
         $element.append(tag);
         $compile(tag)(scope);
     },
     controller: function($scope, $element, $attrs){
         $scope.$watch('Name', function(){            
             console.log(arguments);                    
         });                                          
     }         
});                                     

第二个:

module.directive('createControl', function($compile, $timeout){
   return {   
     transclude: true,
     restrict: 'A',   
     scope: {         
        name: '=name'
     },
     link: function($scope, $element, $attrs){
         // simplified version
         var tag = angular.element('<input type="text" ng-model="name" ng-change="changed(name)">');
         $element.append(tag);
         $compile(tag)(scope);
         $element.find('input').on('change', function(){
             console.log($scope);
         })
     }
});
于 2013-05-12T07:17:14.620 回答