我试图这样做,所以我可以在angularJS应用程序中添加一个带按钮的文本区域。用户喜欢的文本区域可以与向导系统添加内容一样多。显然,每个textarea需要一个不同的ID(因为我打算将它发送到API)所以我在主控制器的范围内创建了一个stageIndex变量。然后在我的新阶段指令中,我这样做,所以它将父div与另一个textarea附加,其中stageIndex作为id ....但它只是用NaN而不是我指定的数字。有任何想法吗? app.controller(“admin”,函数($ scope,$ location,$ http,$ state){
app.controller("admin", function($scope, $location, $http, $state){
$scope.stageIndex = 0;
// My other code here
});
app.directive('newstage', function(){ // This is my buttons directive, hence the element.click()
return function(scope, element, attrs){
element.click(function($scope){
$scope.stageIndex += 1;
element.parent().append("<textarea ng-attr-id="+ 'stage-' + $scope.stageIndex +"></textarea>");
});
}
});
答案 0 :(得分:1)
不会使用$scope
调用您提供给click的回调,并且不会执行依赖注入。将$scope.stageIndex += 1;
替换为scope.stageIndex += 1;
。
点击功能来自jQuery:http://api.jquery.com/click/
app.controller("admin", function($scope, $location, $http, $state){
$scope.stageIndex = 0;
// My other code here
});
app.directive('newstage', function(){ // This is my buttons directive, hence the element.click()
return function(scope, element, attrs){
//element.click(function($scope){ // $scope is undefined here!!!
// I would prefer do the following as it does not require jQuery and will work with jqLite
element.on('click', function () {
// use scope:
scope.stageIndex += 1;
element.parent().append("<textarea ng-attr-id="+ 'stage-' + $scope.stageIndex +"></textarea>");
});
}
});