使用指令的范围而不是控制器的范围

Scope of the directive is used instead of the scope of the controller

在我的项目中,我想访问控制器的 $scope,但是,由于我的范围在指令内,因此使用了指令的 $scope。

这是一个完美的例子。 http://codepen.io/anon/pen/zrmeZw?editors=1010

如果我用 <div> 替换 <card-panel> 标签,一切正常。但是对于 <card-panel> 标签,$scope 使用的是 card-panel scope 而不是 my-controller $scope.

javascript

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

app.directive('cardPanel', function () {
  return {
    transclude: true,
    template: '<div style="background:#fff" layout-margin layout-padding><div ng-transclude></div></div>',
    restrict: 'E',
    link: function (scope, element, attrs) {
    }
  };
});

app.controller('MyController', function($scope) {
  $scope.myContent = '';

  $scope.onChangeListener = function() {
    console.log($scope.myContent);
    console.log("toto");
  }


});

html

<body ng-app="BlankApp" ng-cloak style="background:#f1f1f1" layout>
<div ng-controller="MyController">
  <card-panel layout-margin>
    <h1>MyDemo</h1>

    <md-input-container class="md-block">
      <label> demo </label>
      <input ng-change="onChangeListener()" ng-model="myContent"> </input>
    </md-input-contanier>
  </card-panelr>    
  </div>
</div>


  <!-- Angular Material requires Angular.js Libraries -->
  <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
  <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-animate.min.js"></script>
  <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-aria.min.js"></script>
  <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-messages.min.js"></script>

  <!-- Angular Material Library -->
  <script src="http://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.min.js"></script>

</body>

</html>

好的,我可以吗?

谢谢

我试图通过使用控制器作为语法来解决这个问题。使用 controllerAs 语法,范围不会混淆。

这是工作 code

<div ng-controller="MyController as myctrl">
  <card-panel layout-margin>
    <h1>MyDemo</h1>
    
    <md-input-container class="md-block">
      <label> demo </label>
      
      <input ng-change="myctrl.onChangeListener()" ng-model="myctrl.myContent"/> 
    </md-input-contanier>
  </card-panelr>    
  </div>
</div>

app.controller('MyController', function($scope) {
  var vm = this;
  vm.myContent = '';
  
  vm.onChangeListener = function() {
   
    console.log(vm.myContent);
    console.log("toto");
    
  }
  
  
});

请参考https://github.com/angular/angular.js/wiki/Understanding-Scopes

What happens is that the child scope gets its own property that hides/shadows the parent property of the same name. This is not something AngularJS is doing – this is how JavaScript prototypal inheritance works.

请查看更新后的内容code pen

我已将 scope.mycontent = 'text' 更改为 scope.mycontent = {val: 'text'}。

app.controller('MyController', function($scope) {
  $scope.myContent = {val: ''};

  $scope.onChangeListener = function() {
    console.log($scope.myContent.val);
    console.log("toto");
  }
});