属性上的双向绑定angularjs

问题描述:

属性值没有在双向绑定属性上更新。我需要关注属性吗? 我创建了一个简单的双向绑定。如果在渲染指令后更改minValue,它不会更新新的minValue。属性上的双向绑定angularjs

angular.app('revMgmtApp', []); 
angular.module('revMgmtApp').controller('testCtrl', testCtrl); 

function testCtrl() { 
    var vm = this; 
    vm.counter = 1; 
    vm.minValue = 10; 
}; 



angular.module('revMgmtApp').directive('testDir', function ($compile) { 

    var calController = function() { 
     var vm = this; 
     vm.localOpen = function ($event) { 
      $event.preventDefault(); 
      $event.stopPropagation(); 
      vm.opened = true; 
     } 
    } 

    return { 
     restrict: 'EA', 
     scope: { 
      ngModel: '=', 
      minValue: '=', 
     }, 
     replace: true, 
     link: function (scope, elem, attrs, modelCtrl) { 
      debugger; 
      var el = '<div><span>'; 
      el += '<input type="number" ng-model="vm.ngModel" '; 

      if (scope.vm.minValue != null) { 
       el += " min='" + scope.vm.minValue + "' "; 
      } 
      el += "/>"; 
      var el1 = $compile(el)(scope); 
      elem.replaceWith(el1); 

     }, 
     controller: calController, 
     bindToController: true, 
     controllerAs: 'vm', 
    } 

}) 

    <div ng-app="revMgmtApp" ng-controller="testCtrl as ctrl"> 
    <p> 
     Enter min counter <input type="number" ng-model="ctrl.minValue" /> 
    </p> 

    <test-dir ng-model="ctrl.counter" min-value="ctrl.minValue"></test-dir> 
</div> 

在回答你的问题。是的,您需要关注属性和更新值的功能。

scope.$watch(attrs.testDir, function(value) { 
    //set value here 
    //call update value here 
    }); 

我会按照这个例子中plunker,或在这里下"Creating a Directive that Manipulates the DOM"

但是,你可能会使其成为一个更复杂一点,那么你需要。它是一个独立的范围,所以我们将添加我们想要访问的范围变量作为html中的属性。

为清楚起见,我会在指令HTML重命名属性:

<test-dir mymodel="ctrl.counter" mymin="ctrl.minValue"></test-dir> 

然后,在适用范围,定义保存您将使用范围变量的属性。

scope: { 
     mymodel: '=mymodel', 
     myminval: '=mymin', 
    }, 

。然后,而不是 “链接:” 使用模板。

template: '<div><span><input ng-model="mymodel" min="myminval"/></span></div>'; 

这样,你只结合到您所关心的值。

+0

我使用链接,因为无论我传递给指令的属性,我想应用于输入。 – Santosh 2015-03-03 14:32:27

+0

当您对模板使用双向绑定时,您不必担心任何附加手表,因为该值已绑定。如果您在任何时候更改该值,它都会更新模板值。您还可以获得更多可读代码的附加好处,而不是使用逻辑和连接将元素分开。但是你可以保持它的方式并添加手表,就像在plunker代码中的例子。 – CodeBob 2015-03-04 01:11:33

+0

感谢CodeBob。只有问题与模板是我想通过尽可能多的属性指令和适用于输入字段。我会继续关注属性。 – Santosh 2015-03-04 15:52:19