101

我有两个控制器,并通过 app.factory 函数在它们之间共享数据。

单击链接时,第一个控制器在模型数组 (pluginsDisplayed) 中添加一个小部件。小部件被推送到数组中,并且此更改反映到视图中(使用 ng-repeat 显示数组内容):

<div ng-repeat="pluginD in pluginsDisplayed">
    <div k2plugin pluginname="{{pluginD.name}}" pluginid="{{pluginD.id}}"></div>
</div>

该小部件建立在三个指令之上,k2plugin、remove 和 resize。remove 指令将跨度添加到 k2plugin 指令的模板。单击所述跨度时,共享数组中的右侧元素将被删除Array.splice()。共享数组已正确更新,但更改反映在视图中。但是,当添加另一个元素时,在删除之后,视图会正确刷新,并且不会显示先前删除的元素。

我怎么了?你能解释一下为什么这不起作用吗?有没有更好的方法来做我想要用 AngularJS 做的事情?

这是我的 index.html:

<!doctype html>
<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.min.js">
        </script>
        <script src="main.js"></script>
    </head>
    <body>
        <div ng-app="livePlugins">
            <div ng-controller="pluginlistctrl">
                <span>Add one of {{pluginList.length}} plugins</span>
                <li ng-repeat="plugin in pluginList">
                    <span><a href="" ng-click="add()">{{plugin.name}}</a></span>
                </li>
            </div>
            <div ng-controller="k2ctrl">
                <div ng-repeat="pluginD in pluginsDisplayed">
                    <div k2plugin pluginname="{{pluginD.name}}" pluginid="{{pluginD.id}}"></div>
                </div>
            </div>
        </div>
    </body>
</html>

这是我的 main.js:

var app = angular.module ("livePlugins",[]);

app.factory('Data', function () {
    return {pluginsDisplayed: []};
});

app.controller ("pluginlistctrl", function ($scope, Data) {
    $scope.pluginList = [{name: "plugin1"}, {name:"plugin2"}, {name:"plugin3"}];
    $scope.add = function () {
        console.log ("Called add on", this.plugin.name, this.pluginList);
        var newPlugin = {};
        newPlugin.id = this.plugin.name + '_'  + (new Date()).getTime();
        newPlugin.name = this.plugin.name;
        Data.pluginsDisplayed.push (newPlugin);
    }
})

app.controller ("k2ctrl", function ($scope, Data) {
    $scope.pluginsDisplayed = Data.pluginsDisplayed;

    $scope.remove = function (element) {
        console.log ("Called remove on ", this.pluginid, element);

        var len = $scope.pluginsDisplayed.length;
        var index = -1;

        // Find the element in the array
        for (var i = 0; i < len; i += 1) {
            if ($scope.pluginsDisplayed[i].id === this.pluginid) {
                index = i;
                break;
            }
        }

        // Remove the element
        if (index !== -1) {
            console.log ("removing the element from the array, index: ", index);
            $scope.pluginsDisplayed.splice(index,1);
        }

    }
    $scope.resize = function () {
        console.log ("Called resize on ", this.pluginid);
    }
})

app.directive("k2plugin", function () {
    return {
        restrict: "A",
        scope: true,
        link: function (scope, elements, attrs) {
            console.log ("creating plugin");

            // This won't work immediately. Attribute pluginname will be undefined
            // as soon as this is called.
            scope.pluginname = "Loading...";
            scope.pluginid = attrs.pluginid;

            // Observe changes to interpolated attribute
            attrs.$observe('pluginname', function(value) {
                console.log('pluginname has changed value to ' + value);
                scope.pluginname = attrs.pluginname;
            });

            // Observe changes to interpolated attribute
            attrs.$observe('pluginid', function(value) {
                console.log('pluginid has changed value to ' + value);
                scope.pluginid = attrs.pluginid;
            });
        },
        template: "<div>{{pluginname}} <span resize>_</span> <span remove>X</span>" +
                       "<div>Plugin DIV</div>" +
                  "</div>",
        replace: true
    };
});

app.directive("remove", function () {
    return function (scope, element, attrs) {
        element.bind ("mousedown", function () {
            scope.remove(element);
        })
    };

});

app.directive("resize", function () {
    return function (scope, element, attrs) {
        element.bind ("mousedown", function () {
            scope.resize(element);
        })
    };
});
4

5 回答 5

132

每当您在 AngularJS 之外进行某种形式的操作时,例如使用 jQuery 进行 Ajax 调用,或者将事件绑定到您在此处的元素,您需要让 AngularJS 知道要更新自己。这是您需要做的代码更改:

app.directive("remove", function () {
    return function (scope, element, attrs) {
        element.bind ("mousedown", function () {
            scope.remove(element);
            scope.$apply();
        })
    };

});

app.directive("resize", function () {
    return function (scope, element, attrs) {
        element.bind ("mousedown", function () {
            scope.resize(element);
            scope.$apply();
        })
    };
});

这是关于它的文档:https ://docs.angularjs.org/api/ng/type/$rootScope.Scope#$apply

于 2013-03-18T12:19:53.020 回答
53

如果你$scope.$apply();在之后添加一个权利,$scope.pluginsDisplayed.splice(index,1);那么它就可以工作。

我不确定为什么会发生这种情况,但基本上当 AngularJS 不知道 $scope 已更改时,它需要手动调用 $apply 。我也是 AngularJS 的新手,所以无法更好地解释这一点。我也需要更多地研究它。

我发现这篇很棒的文章很好地解释了它。注意:我认为使用 ng-click (docs)而不是绑定到“mousedown”可能会更好。我在这里编写了一个基于 AngularJS的简单应用程序(http://avinash.me/losh,来源http://github.com/hardfire/losh )。它不是很干净,但它可能会有所帮助。

于 2013-03-18T12:19:54.093 回答
7

我遇到过同样的问题。问题是因为“ng-controller”被定义了两次(在路由和 HTML 中)。

于 2016-07-04T07:56:26.157 回答
1

从 ng-repeat 中删除“按索引跟踪”,它将刷新 DOM

于 2018-07-16T16:21:11.373 回答
0

有一个简单的方法可以做到这一点。好简单。自从我注意到

$scope.yourModel = [];

删除您可以这样做的所有 $scope.yourModel 数组列表

function deleteAnObjectByKey(objects, key) {
    var clonedObjects = Object.assign({}, objects);

     for (var x in clonedObjects)
        if (clonedObjects.hasOwnProperty(x))
             if (clonedObjects[x].id == key)
                 delete clonedObjects[x];

    $scope.yourModel = clonedObjects;
}

$scope.yourModel 将使用 clonedObjects 进行更新。

希望有帮助。

于 2016-10-13T15:25:36.487 回答