2013-05-09 76 views
1

我有一個動態創建輸入標籤的指令。我需要獲取有關更改事件的已創建輸入的值。取而代之的是controller中參數$scope上的name屬性未定義。如何在指令控制器中獲取ng-model值?Angularjs:模型綁定

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); 
    } 
    } 
}); 
+0

你可以分享與HTML指令聲明完整代碼.PLS成立了plunker代碼或的jsfiddle – 2013-05-09 06:41:23

回答

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

1

問題比directive先前執行controller。所以在控制器中應該是$watch ed $scope,而不是添加在directive中的html標籤。不過,我認爲綁定到directivecontroller不應該知道關於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); 
     }) 
    } 
});