Angular.js指令隔离范围不起作用

时间:2014-09-24 10:56:32

标签: angularjs angularjs-directive

我正在建立一个角度指令。 我将属性绑定到指令中的隔离范围,如

scope : {
   contentModel : '='
}



'use strict';

/**
 * Tc markdown directive
 */
var myapp = angular.module('myapp',[]);

myapp.directive('tcMarkdown',[function() {
  var directive = {};
  directive.restrict = 'E';
    directive.template = '<div><div class="row"><!--Content edit pane --><div class="col-md-12"><textarea class="form-control editor" ng-model="someobj.text.data"></textarea></div></div></div>{{contentModel}}';
  directive.scope = {
    contentModel : '='
  };

  directive.link = function(scope, element, attrs) {
    scope.options = {selected : 0};
    scope.$watch(function() {
      return scope.options.selected;
    }, function(newVal) {
      if(newVal===1) {
        scope.buttonCaption = {text : 'Edit'};
      } else if(newVal === 0) {
        scope.buttonCaption = {text : 'Preview'};
      }
    });
  };
  return directive;
}]);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myapp">
<data-tc-markdown content-model="content"></data-tc-markdown>
</div>
&#13;
&#13;
&#13; 双向绑定无效。

当我在textarea中输入时,模型不会更新。

我错过了什么?

2 个答案:

答案 0 :(得分:1)

我看不到您如何将内部contentModel绑定到textarea

这是updated working fiddle

我将someobj.text.data的{​​{1}}替换为ng-model

contentModel

然后我拉出 myapp.directive('tcMarkdown',[function() { var directive = {}; directive.restrict = 'E'; directive.template = '<div><div class="row"><!--Content edit pane --><div class="col-md-12"><textarea class="form-control editor" ng-model="contentModel"></textarea></div></div></div>'; directive.scope = { contentModel : '=' }; directive.link = function(scope, element, attrs) { scope.options = {selected : 0}; scope.$watch(function() { return scope.options.selected; }, function(newVal) { if(newVal===1) { scope.buttonCaption = {text : 'Edit'}; } else if(newVal === 0) { scope.buttonCaption = {text : 'Preview'}; } }); }; return directive; }]); 以确保{{contentModel}}在外部范围内绑定:

{{content}}

这似乎有效。

答案 1 :(得分:0)

&#34;内容&#34;变量应该在指令的外部范围上定义。例如,见下文:我在外部控制器上定义了content1和content2。这些包含值本身。

http://jsfiddle.net/jajtzyhh/3/

var myapp = angular.module('myapp',[]).controller('MyController', ['$scope', function($scope) {
    $scope.content1 = 'Hello';
    $scope.content2 = 'World';
}]);


<div ng-app="myapp">
    <div ng-controller="MyController">
        <data-tc-markdown content-model="content1"></data-tc-markdown>
        <data-tc-markdown content-model="content2"></data-tc-markdown>
    </div>
</div>