如何在自定义Angular指令中更改ng-model范围值?

时间:2015-09-23 21:11:54

标签: javascript angularjs

有以下自定义指令代码:

 angular.module('app.directives', ['ng']).directive('liveSearch', [
    '$compile', '$timeout', function($compile, $timeout) {
      return {
        restrict: 'E',
        replace: true,
        require: 'ngModel',
        scope: {
          ngModel: '=',
          liveSearchCallback: '=',
          liveSearchSelect: '=?',
          liveSearchItemTemplate: '@',
          liveSearchWaitTimeout: '=?',
          liveSearchMaxResultSize: '=?',
          liveSearchResultField: '=?'
        },
        template: "<input type='text' />",
        link: function(scope, element, attrs, controller) {
          scope.$watch('selectedIndex', function(newValue, oldValue) {
            var item;
            item = scope.results[newValue];
            if (item) {
              scope.ngModel = '10';
              element.val(item[attrs.liveSearchResultField]
            }
          });
        }
}}]);

它不是我指令的完整代码,但它足以理解问题。还可以查看代码:

   <live-search class="form-control" id="search1" live-search-callback="mySearchCallback" live-search-result-field="title"ng-model="skill" type="text"></live-search>
   Value: {{ skill }}
   <button class="btn btn-success" type="submit" ng-click="createEmployee">Сохранить</button>

我的控制器代码:

$scope.createEmployee = function() {
        console.log($scope.skill);
};

正如您所看到的,我的自定义指令具有&#39; ng-model&#39;属性名称为变量&#39;技能&#39;。我怎样才能改变技能&#39;我的自定义指令中的值?我的方式不起作用。提前谢谢!

2 个答案:

答案 0 :(得分:3)

link:尝试使用

link:function(scope, element, attrs, ngModel){
    scope.$watch('selectedIndex', function(newValue, oldValue) {
       var item;
       item = scope.results[newValue];
       if (item) {
         ngModel.$setViewValue(10);
         ngModel.$render() // will update the input value as well
         element.val(item[attrs.liveSearchResultField];
       }
    });
}

此外,您似乎错过了在HTML

中分隔ng-model属性之间的空间
<live-search class="form-control" id="search1" live-search-callback="mySearchCallback" live-search-result-field="title" ng-model="skill" type="text"></live-search>

请参阅文档here

答案 1 :(得分:1)

使用require: 'ngModel'时,传递给link函数的第4个参数为ngModelController。使用方法$setViewValue更新传递给您的指令的ngModel值,如果您的视图也需要更新,请调用$render()

link: function(scope, element, attrs, ngModelController) {
  scope.$watch('selectedIndex', function(newValue, oldValue) {
    var item;
    item = scope.results[newValue];
    if (item) {
      ngModelController.$setViewValue(10);
      ngModelController.$render();
      element.val(item[attrs.liveSearchResultField]
    }
  });
}