Dr.Knowitall
Dr.Knowitall

Reputation: 10498

ng-model is not updating in nested directive

I have text-angular embedded in an directive that has the scope variable... scope.htmlContent.content. In the directive I have

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()
})
}

Anyway, ng-model is not updating properly. Only when I explicitly set scope.htmlContent.content in the beginning of the link function out side of some async fxn then it works. How can I update ng-model?

Upvotes: 0

Views: 437

Answers (1)

V31
V31

Reputation: 7666

You need to create a factory for your http get call something like this:

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

Then in your directive you need to inject the factory

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

Hope it helps!!

Upvotes: 1

Related Questions