2015-12-30 82 views
-1

我意識到有類似的問題已經在這個SO上,但我找不到解決我的問題。訪問控制器中的指令值

我有以下指令,提取光標葉(模糊)的輸入框鍵和值:

.directive('updateOneField', function() { 
    return { 
    restrict: 'A', 
    scope: [], 
    link: function(scope, element, attr) { 

     element.bind('blur', function() { 
     var key = attr.ngModel.split('.'); 
     key = key[key.length - 1]; 

     // Get the input value 
     var value = element[0].value; 


     }); 
    } 
    }; 
}); 

這將潛在地跨越多個控制器使用,所以我的問題是我如何訪問來自任何控制器的keyvalue值?

+0

http://www.undefinednull.com/2014/02/11/mastering-the-scope-of-a-directive-in-angularjs /我剛剛發現這個博客感謝你的問題,它真的真的解釋** scope **在指令和指令非常清楚。看看,感謝upvote :) – katmanco

回答

0

如果我理解正確,您正試圖訪問ngModel的值,這樣做的最「有效的方法」就是在您的指令中要求ngModelController;

return { 
    restrict: 'A', 
    require: 'ngModel', 
    link: function(scope, element, attrs, ngModelCtrl) { 
     element.bind('blur', function() { 
      var model = ngModelCtrl.$modelValue; 
     }); 
    } 
}; 

您可以找到有關ngModelController here

0

有更多的信息,您可以在控制器範圍變量傳遞給你的指令,並使用這個變量來從指令訪問值。

<input type="text" update-one-field my-scope="myVariable" /> 

這裏,myVariable是控制器的變量。現在

$scope.myVariable = {}; 

,更新您的指令就是這樣,

.directive('updateOneField', function() { 
    return { 
     restrict: 'A', 
     scope: { 
      myScope: '=' 
     }, 
     link: function(scope, element, attr) { 

      element.bind('blur', function() { 
       var key = attr.ngModel.split('.'); 
       key = key[key.length - 1]; 

       // Get the input value 
       var value = element[0].value; 

       // Assign key and value to controller variable 
       scope.myScope = {}; 
       scope.myScope.Key = key; 
       scope.myScope.Value = value; 
      }); 
     } 
    }; 
}); 

現在,你可以從控制器就像訪問key & value

// Code inside your controller 
$scope.myVariable.Key; // Get key from the directive 
$scope.myVariable.Value; // Get value from the directive 

希望這會有所幫助。如果您對此有任何疑問,請隨時添加評論。

0

你在指令聲明一個錯字:

.directive('updateOneField', function() { 
    return { 
    restrict: 'A', 
    // her -------------------------------> scope: [], 
    scope : {}, 
    link: function(scope, element, attr) { 

     element.bind('blur', function() { 
     var key = attr.ngModel.split('.'); 
     key = key[key.length - 1]; 

     // Get the input value 
     var value = element[0].value; 


     }); 
    } 
    }; 
}); 
相關問題