当前位置: 动力学知识库 > 问答 > 编程问答 >

angularjs - How to update an input's value after calling $setViewValue

问题描述:

I have a form input with a ng-model as well as my custom directive which reads cookie data and should set the input value:

<form>

<input type="text" id="name" ng-model="name" my-cookie-directive>

</form>

My directive:

angular.module('myApp.directives').directive('myCookieDirective', ['CookieService', function(CookieService) {

return {

require: 'ngModel',

link: function(scope, elem, attrs, ctrl) {

var cookieVal = CookieService.getCookie(attrs.ngModel);

if(cookieVal != '') {

ctrl.$setViewValue(cookieVal);

elem.val(cookieVal); //not very cool hum?

}

}

};

}]);

When logging ctrl.$modelValue I can see that the right cookie data was set to my controller variable name but the input stays blank. I know that $setViewValue does not trigger a $digest and therefore tried ctrl.$render() but nothing happens.

I ended up using jQuery to set the input's value which is not satisfying at all.

Thanks in advance :)

网友答案:

You are correct in not wanting to use jQuery to set the input's value. Why would you be using Angular if you are going to do that then?

You can see a new Plunker here, using a different approach to the ones being mentioned. My suggestion: use NgModelController when you want to handle validations and format the model value.

For your current situation, you can use an isolated scope in the directive, and pass to it the scope property you want to update with the cookie value. Then in the directive, you can simply do:

scope.cookieField = cookieVal;

And Angular will handle the data binding and update the view value to match the model value. Plus, this is completely reusable.

网友答案:

Use $render and wrap everything in a function passed to $evalAsync:

if(cookieVal !== '') {
    scope.$evalAsync(function(){
      ctrl.$setViewValue(cookieVal);
      ctrl.$render();
    });
}

Plunker demo

分享给朋友:
您可能感兴趣的文章:
随机阅读: