2016-05-30 68 views
0

的屬性中我有其中包含輸入的「nibTextbox」指令,輸入具有ng-model,我希望ng-model值始終可用於「值」指令的屬性。(我不想用替換)從內部輸入指令獲取ng-model並將其放入指令

angular.module('nib', []) 
    .directive('nibTextbox', function() { 
     return { 
      restrict: 'E', 
      scope: { 
       id: '@', 
       title: '@', 
      }, 
      compile: function (element, attributes) { 

       var linkFunction = function (scope, element, attributes) { 

       } 
       return linkFunction; 
      }, 
      controller: ['$scope', '$http', function ($scope, $http) { 

      }], 
      template: '<div value="{{nibTextBoxValue}}"><img src="" alt=""/><label>{{title}}</label><input id="{{id}}_txt" type="text" ng-model="nibTextBoxValue"></input></div>' 
     }; 
    }); 


<nib-textbox id="ngArmin1" title="ngArmin1Title" value="{{nibTextBoxValue}}"></nib-textbox> 

回答

0

value是無效的<div>元素。所以我們將其更改爲data-div。 這是怎麼看起來或多或少的(我一般用的打字稿工作,但我會用普通的JavaScript來傳遞的想法):

angular.module('nib', []) 
    .directive('nibTextbox', function() { 
     return { 
      restrict: 'E', 
      scope: { 
       id: '@', 
       title: '@', 
      }, 
      compile: function (element, attributes) { 

       var linkFunction = function (scope, element, attributes) { 

       } 
       return linkFunction; 
      }, 
      // Injected $element for manipulating attributes     
      controller: ['$scope', '$http', '$element', function ($scope, $http, $element) { 


       $scope.$watch("nibTextBoxValue", function(newValue) { 
       $element.attr("data-value", newValue); 
      }); 
     }], 
      templateUrl: 'template.html' // Extracting the template to a file 
     }; 
    }); 

的指令模板(template.html):

<div> 
    <img src="" alt=""/><label>{{title}}</label> 
    <input id="{{id}}_txt" type="text" ng-model="nibTextBoxValue"></input> 
    </div> 

此外,從你的指令刪除value屬性:

<nib-textbox id="ngArmin1" title="ngArmin1Title"></nib-textbox>

+0

感謝的人,你是個好孩子:d,非常感謝,我會改變你的答案有點和它的工作,這個想法是使用$表(不需要。使用數據值,只有值) –

0

答案:使用$手錶 變化控制器定義是:

controller: ['$scope', '$http', '$element', function ($scope, $http, $element) { 
        $scope.$watch("nibTextBoxValue", function (nv) { 
         $element.attr("value", nv); 
        }); 
       }]