为什么我的$ scope不能反映我的控制器被初始化?

时间:2014-01-15 02:34:51

标签: angularjs angularjs-directive angularjs-scope

问题:

为什么{{ name }}导致空白?

Plunker:

http://plnkr.co/edit/32t8u4VL9BiuhHcC80LF?p=preview

脚本:

var app = angular.module('app', []);

app.controller('MainCtrl', function($scope) {
  $scope.name = 'World';
});

app.directive('portal', function () {
  return {
    restrict: 'E',
    transclude: true,
    template: '<div><span>Header</span><div ng-transclude></div><span>Footer</span></div>'
  }
})

HTML:

<portal ng-app="app" ng-controller="MainCtrl">
  <p>Hello {{ name }}, let's see if Angular is working at all... 1 + 2 = {{ 1 + 2 + '!' }}</p>
</portal>

2 个答案:

答案 0 :(得分:2)

ng-appmg-controller放在父<div/>上,事情会按预期运作。

<div ng-app="app" ng-controller="MainCtrl">
    <portal>
      <p>Hello {{ name }}, let's see if Angular is working at all... 1 + 2 = {{ 1 + 2 + '!' }}</p>
    </portal>
</div>

答案 1 :(得分:1)

将门户网站更改为div,您会发现它的指令不起作用,而不是您的控制器。

这有效:

  <div ng-app="app" ng-controller="MainCtrl">
    <portal>
      <p>Hello {{ name }}, let's see if Angular is working at all... 1 + 2 = {{ 1 + 2 + '!' }}</p>
    </portal>
  </div>