我有一个简单的网络应用程序,用名字和他们居住的城市列出用户。 当用户单击其名称或城市时,元素将被两个输入元素替换。一个用于名称,第二个用于他们居住的城市。输入元素将帮助用户更新他们的名字和城市。简单的AngularJS指令DOM操作。
我遇到的问题是,当有人点击名称或城市元素时,在您单击info指令中的保存更新按钮之前,绑定文本不会显示在输入元素中。
这是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);
});
}
}
});
答案 0 :(得分:1)
click
事件是 async 。这意味着您的范围不了解模型更改。只需包装这两行:
var dataScoped = $compile(html)(scope);
element.replaceWith(dataScoped);
使用scope.$apply
:
scope.$apply(function(){
var dataScoped = $compile(html)(scope);
element.replaceWith(dataScoped);
});