在单击按钮之前,不会显示已编译的文本绑定

Compiled Text Bind Does Not Show Up Until You Click A Button

本文关键字:显示 编译 绑定 文本 按钮 单击      更新时间:2023-09-26

我有一个简单的网络应用程序,按名字和他们居住的城市列出用户。当用户单击其名称或城市时,元素将被两个输入元素替换。一个是名字,第二个是他们居住的城市。输入元素将帮助用户更新他们的名字和城市。简单的 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); 
            });

        }
    }
});

click事件是异步的。这意味着您的示波器不知道模型更改。只需将这两行换行:

 var dataScoped = $compile(html)(scope);
 element.replaceWith(dataScoped); 

带有scope.$apply

 scope.$apply(function(){
     var dataScoped = $compile(html)(scope);
     element.replaceWith(dataScoped); 
 });

工作: http://plnkr.co/edit/Z72AfK?p=preview