簡體   English   中英

Angular JS - 指令中的數據綁定不起作用

[英]Angular JS - Data binding in directive is not working

我在指令中有一個數據綁定問題,它調用另一個指令。

這是主要指令:

var app = angular.module('app');

app.directive("myMainDirective", function ($http) {
return {
    scope: {
        paramId: '='
    },
    link: function (scope) {
        $http.get('some/url/' + scope.paramId+ '.json'
        ).success(function (data) {
                scope.idFromServer = data;
            });
    },
    template: '<span other-directive id="idFromServer"></span>'
}
});

這是另一個指令:

var app = angular.module('app');

app.directive("otherDirective", ['$http', function(http) {
return {
    template: "<span>{{name}}</span>",
    scope: {
        id: "="
    },
    link: function(scope) {
        http.get('another/url/' + scope.id + '.json').then(function(result) {
            scope.name = result.data.name;
        }, function(err) {
            scope.name = "unknown";
        });
    }
}
}])

以及調用主要指令的html代碼:

<span my-main-directive param-id="myObject.id"></span>

當調用“other-directive”時,“idFromServer”不綁定,並且是“未定義”,因此它會導致顯示“未定義”。

我可能錯過了一些愚蠢的東西,但我看不出是什么......(我的代碼很可能不是最好的,我對angularjs很新,特別是指令,我嘗試了很多方法實現我想要的。)

根據我的評論,這是使用范圍可能有效的一種方式。$ watch:

scope.$watch('id', function(id) {
    $http.get('some/url/' + id + '.json')
        .success(function (data) {
            scope.idFromServer = data;
        });
};

這將進入嵌套指令的link函數內部。

我建議的方法之一就是不要在idFromServer變量上使用雙向( = )綁定,使用{{idFromServer}}插值指令為屬性賦值,然后使用$attr.$observe它會在插值時調用被評估。

myMainDirective

app.directive("myMainDirective", function ($http) {
return {
    scope: {
        paramId: '='
    },
    link: function (scope) {
        $http.get('some/url/' + scope.paramId+ '.json'
        ).success(function (data) {
                scope.idFromServer = data;
            });
    },
    template: '<span other-directive id="{{idFromServer}}"></span>'
}
});

otherDirective

app.directive("otherDirective", ['$http', function(http) {
    return {
        template: "<span>{{name}}</span>",
        scope: true, //isolated scope
        link: function(scope, element, attr) {
            attr.$observe(attr.id, function(newVal) {
                http.get('another/url/' + newVal + '.json').then(function(result) {
                    scope.name = result.data.name;
                }, function(err) {
                    scope.name = "unknown";
                });
            });
        }
    }
}])

由於javascript是異步的,因此兩個ajax請求基本上同時運行,並且當other-directive的請求運行時, id undefined

如果您想嘗試測試,只需為idFromServer設置默認值。 other-directive的請求將以默認值運行。

編輯:回應你的評論,這是一個非常廣泛的問題,有很多解決方案。 我能給你的最好答案就是,從來沒有在你的鏈接函數中運行任何邏輯,只需定義指令的行為和屬性 - 這就是鏈接函數的用途。 模板立即使用,您無法更改。

在這種情況下,您可以獲取在父作用域中准備的數據並在屬性中傳遞數據。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM