javascript - ng-model 未在嵌套指令中更新

标签 javascript angularjs angularjs-directive angularjs-scope

我在具有范围变量的指令中嵌入了文本 Angular ...scope.htmlContent.content。在指令中我有

template:
'''
// This updates just fine. I use it to debug so I will take this out from time to time
<p ng-bind='htmlContent.content'></p>
// ng-model htmlContent.content stays blank and does not update
<text-angular ng-model='htmlContent.content'>
</text-angular>
''',
link: function(scope, ele, attr, ctrl) {
//some code
$http({
  method: 'GET'
  url: 'someurl.com'
}).success(function(data,headers,config) {
  // This does not update text-angular
  scope.htmlContent.content = data;
  // If I add this, it will error out
  scope.$apply()
})
}

无论如何,ng-model 没有正确更新。仅当我在某些异步 fxn 之外的链接函数的开头显式设置scope.htmlContent.content 时,它才起作用。如何更新 ng-model?

最佳答案

您需要为您的 http get 调用创建一个工厂,如下所示:

//Please change it as per your needs
app.factory('factoryProvider', function(){
    return {
    yourData:function(callback){
        $http.get('url').success(callback); 
    }
   }
});

然后在你的指令中你需要注入(inject)工厂

app.directive('myDiv',['factoryProvider', function(factoryProvider) {
    return {
        restrict: 'E',
        replace: true,
        template: '<p>{{name}}</p>',
        controller: function($scope) {
        },
        link: function(scope) {
            scope.data=factoryProvider.yourData;
        }
    };
}]);

希望对你有帮助!!

关于javascript - ng-model 未在嵌套指令中更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24751073/

相关文章:

javascript - ng-route 注入(inject)器错误 :modulerr [$injector:modulerr] http://errors. angularjs.org/1.3.14/$injector/modulerr

javascript - 正则表达式匹配后面有空格或没有空格的情况

javascript - 如何用javascript代码删除缓存?

javascript - 浏览器窗口关闭和选项卡关闭

angularjs - Angular 更新本地存储单个对象

javascript - 对多个选项使用 Angular 指令

javascript - 如何在 JSBin 中导入 lodash?

javascript - 在 Angular 中使用 es6 测试服务类

javascript - 在 Angular 1.5 中刷新浏览器时如何保留同一页面?

javascript - 如何使用 ngrepeat 和双向绑定(bind)获取指令的隔离范围?