我在具有范围变量的指令中嵌入了文本 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/