Angularjs指令范围

时间:2014-09-29 19:33:33

标签: angularjs angularjs-directive angularjs-scope

我试图创建一个指令,并且遇到了scope对象的一些问题。在创建一个显示正在发生的事情的傻瓜时,我注意到我已经接近,但不太确定我误解了什么。

如果我的指令看起来像这样:

angular.module('inputExample', [])
       .directive('test',
       function() { 
         return{
         restrict: 'E',
         link: function(scope){
           scope.testInput = 1;
           scope.$watch(
             'testInput',
             function(newTestInput){
               console.log(newTestInput);
             },
             false);
         }
         }
       });

并在视图中使用该指令,如下所示:

  <test>
    <input data-ng-model="testInput" />
    <div>
      {{testInput}}
    </div>

div似乎正确更新,并且有一条消息记录到控制台,正如我所料。

如果我创建了这样的指令:

angular.module('inputExample', [])
          .directive('example',
           function() { 
             return{
            scope: {
              'settings': '@'
            },
             restrict: 'E',
             link: function(scope){
               scope.exampleInput = 1;
               scope.$watch(
                 'exampleInput',
                 function(newTestInput){
                   console.log(newTestInput);
                 },
                 false);
             }
             }
           });
  </test>

并在以下视图中使用它:

  <example>
    <input data-ng-model="exampleInput" />
    <div>
      {{exampleInput}}
    </div>
  </example>

然后div似乎得到更新,但没有消息记录到控制台。似乎$ watch并不工作。有人可以告诉我我做错了吗?

这是plunkr

提前感谢您提供的任何帮助。

1 个答案:

答案 0 :(得分:2)

示例的问题在于您将HTML放在指令标记中。它们应该在您的模板中。

此代码有效

   angular.module('inputExample', [])
          .directive('example',
           function() { 
             return{
            scope: {
              'settings': '@'
            },
             restrict: 'E',
             template: '<input data-ng-model="exampleInput" /><div>{{exampleInput}}</div>',
             link: function(scope){
               scope.exampleInput = 1;
               scope.$watch(
                 'exampleInput',
                 function(newTestInput){
                   console.log(newTestInput);
                 },
                 false);
             }
             }
           });

视图只是

<example></example>