没有控制器的指令中模板绑定的范围是什么

时间:2015-10-26 04:40:39

标签: angularjs angularjs-directive

Here是一个简单的角度应用程序。它根据用户单击按钮显示/隐藏文本。

<div ng-controller="exampleController as ctrl">
  <example></example>
</div>


app.controller('exampleController', function () {});
app.directive('example', function () {
  return {
    restrict: 'E',
    template: '<p ng-show=\"showMe\">Text to show</p><button ng-click=\"clickMe()\">Click me</button>',
    scope: {},
    link: function (scope) {
        scope.clickMe = function () {
            scope.showMe = !scope.showMe;
        };
    }
  };
});

当我卸下控制器时,它不起作用。请注意,该指令创建了一个隔离范围,因此我的理解是它并不依赖于控制器范围。

<div>
  <example></example>
</div>

app.directive('example', function () {
  return {
    restrict: 'E',
    template: '<p ng-show=\"showMe\">Text to show</p><button ng-click=\"clickMe()\">Click me</button>',
    scope: {},
    link: function (scope) {
        scope.clickMe = function () {
            scope.showMe = !scope.showMe;
        };
    }
  };
});

这里有什么问题?

1 个答案:

答案 0 :(得分:1)

但无论如何你应该有ng-app

<body ng-app="demo">
    <div>
        <example></example>
    </div>
</body>

var app = angular.module("demo", [])    

app.directive('example', function () {

    return {
        restrict: 'E',
        template: '<p ng-show=\"showMe\">Text to show</p><button ng-click=\"clickMe()\">Click me</button>',
        scope: {},
        link: function (scope) {
            scope.clickMe = function () {
                scope.showMe = !scope.showMe;
            };
        }
    };
});

Fiddle