【问题标题】:AngularJs Directive don't update itself for source element's attribute updatesAngularJs 指令不会为源元素的属性更新而自行更新
【发布时间】:2016-06-11 13:34:59
【问题描述】:

几乎尝试了所有方法,但没有成功。

我只想在单击类名为“ion-android-favorite-outline”的元素时执行操作。

我的源元素如下所示

<i id="{{product.product_code}}" class="icon ion-android-favorite-outline"></i>

我可以在指令代码中使用“restrict:'C'”来做到这一点。

在指令中,一旦完成数据处理,我将源元素的类更改为“ion-android-favorite”,如下所示。

.directive(
    "ionAndroidFavoriteOutline",
    function(sessionStorageService, productService){
        return{
            restrict: 'C',
            link: function(scope, element, attrs) {
                element.bind("click" , function(e){
                    var productCode =   attrs.id;
                    console.log(attrs.class);   // on every click i get class name as 'ion-android-favorite-outline' event though html has class name as 'ion-android-favorite'
                    if (sessionStorageService.isLoggedIn()) {
                        productService.trackProduct(productCode).then(function(response){
                            if (response.data.status == "success") {
                                element.removeClass("ion-android-favorite-outline").addClass("ion-android-favorite");
                            } else {
                                element.removeClass("ion-android-favorite").addClass("ion-android-favorite-outline");
                            }
                        });

                        scope.$apply();
                    }

我可以看到源元素的类名发生了变化,并且它在 UI 中的反映也是如此。

但是,如果我再次单击源元素(在之前的单击操作中更改了其类)仍会调用指令代码。

为什么?

我尝试了 scope.$apply ,replace: true 等...但没有解决方法。

请帮忙。

【问题讨论】:

  • 因为您需要在标签 上取消绑定事件 click

标签: angularjs directive


【解决方案1】:

@stephan, answered correctly.

element.unbind("click");

【讨论】:

    【解决方案2】:

    您可以使用如下指令:

     <i id="{{product.product_code}}" class="ion-android-favorite-outline" ion-android-favorite-outline></i>
    

    【讨论】:

    • 阿里,它不工作。将“ion-android-favorite-outline”作为指令的想法是什么?我应该将我的指令定义更改为restrict: A 吗?你能解释一下吗?
    猜你喜欢
    • 1970-01-01
    • 2016-01-07
    • 1970-01-01
    • 2017-05-28
    • 1970-01-01
    • 2014-03-02
    • 1970-01-01
    • 2018-03-28
    • 1970-01-01
    相关资源
    最近更新 更多