Angular JS - 指令中的数据绑定不起作用

Mat*_*gre 5 javascript angularjs angularjs-directive angularjs-scope

我在指令中有一个数据绑定问题,它调用另一个指令.

这是主要指令:

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>'
}
});
Run Code Online (Sandbox Code Playgroud)

这是另一个指令:

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";
        });
    }
}
}])
Run Code Online (Sandbox Code Playgroud)

以及调用主要指令的html代码:

<span my-main-directive param-id="myObject.id"></span>
Run Code Online (Sandbox Code Playgroud)

当调用"other-directive"时,"idFromServer"不绑定,并且是"未定义",因此它会导致显示"未定义".

我可能错过了一些愚蠢的东西,但我看不出是什么......(我的代码很可能不是最好的,我对angularjs很新,特别是指令,我尝试了很多方法实现我想要的.)

Ben*_*ack 4

根据我的评论,这是一种可能有效的方法,使用范围。$watch:

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

这将进入嵌套指令的链接函数内部。