ng-model没有在嵌套指令中更新

时间:2014-07-15 06:15:43

标签: javascript angularjs angularjs-directive angularjs-scope

我将text-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?

1 个答案:

答案 0 :(得分:1)

您需要为您的http get调用创建一个工厂:

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

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

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;
        }
    };
}]);

希望它有所帮助!!

相关问题