我有一个简单的网络应用程序,它按名字和他们居住的城市列出用户。当用户点击他们的名字或城市时,这些元素将被两个输入元素替换。一个是姓名,第二个是他们居住的城市。输入元素将帮助用户更新他们的名字和城市。简单的 AngularJS 指令 DOM 操作。
我遇到的问题是,当有人单击名称或城市元素时,绑定文本不会显示在输入元素中,直到您单击我的信息指令中的保存更新按钮。
这是 HTML:
<!DOCTYPE HTML>
<html id="ng-app" ng-app="app">
<head>
<meta charset="UTF-8">
<title>JS</title>
</head>
<body>
<div ng-controller="UserController">
<div>
Search:
<input placeholder="search customers" data-ng-model="name" />
</div>
<div >
<h4>Customers</h4>
<ul>
<li ng-repeat="cust in customers | filter:name" >
<!-- My Info Directive -->
<info update="updateCustomer(this)" name="cust.name" city="cust.city"></info>
</li>
</ul>
</div>
<div>
Name: <input type="text" ng-model="newCustomer.name" /><br />
City: <input type="text" ng-model="newCustomer.city" /><br />
<button ng-click="addCustomer()" >Add New Customer</button>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
<script src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
<script type="text/javascript" src="main.js"></script>
</body>
</html>
这是 JavaScript (main.js):
var app = angular.module("app",[])
.controller('UserController',function ControllerOne($scope){
$scope.customers = [
{name:"Milo",city:"London"},
{name:"John", city:"New York"},
{name:"Alfred",city:"Oslo"}
];
$scope.addCustomer = function (){
$scope.customers.push({name:$scope.newCustomer.name, city:$scope.newCustomer.city});
$scope.newCustomer.name = $scope.newCustomer.city = "";
};
$scope.updateCustomer = function(ele){
console.log("Name: " + ele.name + " City: " + ele.city);
}
})
.directive("info",function($compile){
return {
restrict :"E",
scope:{
name:"=",
city:"=",
update:"&"
},
template:"<div>{{name}}-{{city}}</div>",
link:function(scope,element,attrs){
element.bind("click",function(){
var html = "<input name='name' ng-model='name'/><input name='city'ng-model='city'/><button ng-click='update(this)'>Save Update</button>";
var dataScoped = $compile(html)(scope);
element.replaceWith(dataScoped);
});
}
}
});