附加到與Angular.JS指令綁定的數組

[英]Appending to an array that's tied to an Angular.JS directive


In one of my Angular.JS controllers, I have the following:

在我的一個Angular.JS控制器中,我有以下內容:

app.controller("MyController", ["$scope", function($scope){
    $scope.messages = [
        new Message(1),
        new Message(2)
    ];
    $scope.addMessage = function(x) { $scope.messages.push(new Message(x)); }
}]);

Then in my main HTML page, I have

然后在我的主HTML頁面中,我有

<message message="message" ng-repeat="message in messages">

This is bound to a directive:

這是一個指令:

app.directive("message", function() {
    return {
        restrict: "E",
        scope: {
            message: "="
        },
        templateUrl: "js/Directives/message.html"
   };
});

The template file is:

模板文件是:

<li class="message">{{message.msg}} </li>

However, when I call addMessage on the controller, while it does add to $scope.messsages, it doesn't actually refresh the ng-repeat and display the new message. How can I do this?

但是,當我在控制器上調用addMessage時,它確實添加到$ scope.messsages,它實際上不會刷新ng-repeat並顯示新消息。我怎樣才能做到這一點?

1 个解决方案

#1


1  

I would suggest some structural changes in your directive.

我建議你的指令進行一些結構性的改變。

First of all, why not refer the original array itself instead of referring value at each iteration ??

首先,為什么不在每次迭代時引用原始數組本身而不是引用值?

<message messages="messages">

Then you can actually move ng-repeat part in your directive template, [You must note that since you're using = in message: "=", = binds a local/directive scope property to a parent scope property. So with =, you use the parent model/scope property name as the value of the DOM attribute. ].

然后你可以在你的指令模板中實際移動ng-repeat部分,[你必須注意,因為你在消息中使用=:“=”,=將本地/指令范圍屬性綁定到父范圍屬性。因此,使用=,您可以使用父模型/范圍屬性名稱作為DOM屬性的值。 ]。

Hence your directive will look like :

因此,您的指令將如下所示:

app.directive("message", function() {
    return {
        restrict: "E",
        scope: {
            messages: "="
        },
        templateUrl: "js/Directives/message.html"
   };
});

and the subsequent template will look something like this :

后續模板看起來像這樣:

    <ul>
        <li ng-repeat="message in messages" class="message">{{message.msg}} </li>
    </ul>

You can find a demo plunker here

你可以在這里找到一個演示插件


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2015/07/10/729db9b1c335b674c4c139b29a47465e.html



 
粤ICP备14056181号  © 2014-2020 ITdaan.com