javascript - Angular JS - 指令中的数据绑定(bind)不起作用

标签 javascript angularjs angularjs-directive angularjs-scope

我有一个指令内的数据绑定(bind)问题,该指令调用另一个指令。

这是主要指令:

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”没有绑定(bind),是“undefined”,所以显示为“undefined”。

我可能遗漏了一些愚蠢的东西,但我不明白是什么...... (我的代码可能不是最好的,我是 angularjs 的新手,特别是指令,我尝试了很多方法来完成我想要的。)

最佳答案

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

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

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

关于javascript - Angular JS - 指令中的数据绑定(bind)不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29707603/

相关文章:

angularjs - 如何编写一个指令,可以使用 Angular 指令渲染一些 html 代码,并将其显示为文本?

javascript - Backbone.js 集合不添加对象

javascript - 如何使用 Yesod 构建 AngularJS 应用程序

JavaScript setTimeOut 函数不起作用

javascript - 将 json 数组更改为 angularjs 中的表

javascript - 带有 Cookie 的 Ng 模型

javascript - 使用 Json 删除 ASP.NET 中不需要的符号

javascript - 为什么编译运行多次 - Angular Directive

javascript - 使用 AngularJS 在滚动条上隐藏一个 div

javascript - 当选择值为 'others' 时,输入字段应隐藏