更改附加每个文本

时间:2016-01-12 05:54:22

标签: javascript jquery html angularjs

我没有使用追加事件正确获得结果,而是在添加每个名称时使用ng-repeat。你能帮我解决一下如何从一个输入字段中更改添加的每个名字。告诉我不使用ng-repeat,因为ng-repeat功能对我的进一步运行功能不起作用,你可以使用jquery或javascript解决这个问题,如果不使用ng-repeat就可以。提前致谢.. Here is JSBin



var app = angular.module('myapp', ['ngSanitize']);

app.controller('AddCtrl', function ($scope, $compile) {

    $scope.my = {name: 'untitled'};
       $scope.add_Name = function (index) {
        var namehtml = '<label ng-click="selectName($index)">{{my.name}} //click<br/></label>';
        var name = $compile(namehtml)($scope);
        angular.element(document.getElementById('add')).append(name);
    };
   
    $scope.selectName = function (index) {
        $scope.showName = true;
    };

});
&#13;
<!DOCTYPE html>
<html ng-app="myapp">

<head>
	<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0-beta.2/angular.min.js"></script>
	<script src="https://code.angularjs.org/1.5.0-rc.0/angular-sanitize.min.js"></script>
</head>

<body ng-controller="AddCtrl">
	<button ng-click="add_Name($index)">Add Names</button>
	<div id="add"></div><br/>

	<form ng-show="showName">
      <label>Name Change(?)</label><br/>
	  <input ng-model="my.name">
	</form>
</body>

</html>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

  

ng-repeat对于此类案件是完美的。不确定是什么让你避免这种情况。

您可以拥有counter,每次添加Name时都会增加counter name。同样将selectName作为selectName函数的参数传递。

每次调用model时,参数值都将设置为var app = angular.module('plunker', []); app.controller('MainCtrl', function($scope, $compile) { $scope.my = { name: 'untitled' }; var counter = 0; $scope.add_Name = function(index) { var myName = 'untitled' + counter; var namehtml = '<label ng-click="selectName(\'' + myName + '\')">' + myName + ' //click<br/></label>'; var name = $compile(namehtml)($scope); angular.element(document.getElementById('add')).append(name); ++counter; }; $scope.selectName = function(val) { $scope.my.name = val; $scope.showName = true; }; });

试试这个:

&#13;
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>

<body ng-app="plunker" ng-controller="MainCtrl">
  <button ng-click="add_Name($index)">Add Names</button>
  <div id="add"></div>
  <br/>

  <form ng-show="showName">
    <label>Name Change(?)</label>
    <br/>
    <input ng-model="my.name">
  </form>
</body>
&#13;
{{1}}
&#13;
&#13;
&#13;

Working demo