Scoping issue when setting ngModel from a directive

后端 未结 2 1205
闹比i
闹比i 2021-01-26 01:13

I have a directive which looks something like:

var myApp = angular.module(\'myApp\',[])
    .directive(\"test\", function() {
      return {
        template: \'         


        
2条回答
  •  遥遥无期
    2021-01-26 02:01

    For this scenario ngModel probably isn't the right solution. That's mostly for binding values to forms to doing things like marking them dirty and validation...

    Here you could just use a two way binding from an isolated scope, like so:

    app.directive('test', function() {
       return {
          restrict: 'E',
          scope: { 
             target: '=target',
             setTo: '@setTo'
          },
          template: '',
          controller: function($scope) {
              $scope.setValue = function() {
                  $scope.target = $scope.setTo;
              };
              //HACK: to get rid of strange behavior mentioned in comments
              $scope.$watch('target',function(){});
          }
       };
    });
    

提交回复
热议问题