为什么我的示波器没有显示指令?

时间:2016-10-21 21:44:48

标签: javascript angularjs angularjs-directive angularjs-scope

我正在使用自定义控制器创建一个指令并测试范围。我想测试该指令是否具有索引页面的范围,但ng-show不起作用。

HTML

<div class="main">
<div ng-controller="rl">

<book-genres></book-genres>
<review-form ng-show="reviewFormCtrl.rating == 1"></review-form>
<input ng-click="reviewFormCtrl.rating = 3" type="button" value="Test" /> 

</div>

</div>

部分:

<div>
    Review Forms : {{ rating }}

</div>

控制器:

myApp.controller('rl', function(){

});

myApp.directive('reviewForm',  function(){
    return {
        restrict: 'E',
        templateUrl: 'partials/review-form.html',
        replace: true,
        scope: true,
        controller: function($scope){
                $scope.rating = 1;
        },
        controllerAs: 'reviewFormCtrl'
    };
});

2 个答案:

答案 0 :(得分:1)

因为您使用控制器作为语法(例如controllerAs: 'reviewFormCtrl'),所以您应该将评级附加到控制器而不是范围。

这应该有效

myApp.directive('reviewForm',  function(){
  return {
    restrict: 'E',
    templateUrl: 'partials/review-form.html',
    replace: true,
    scope: true,
    controller: function(){
      this.rating = 1;  //change here
    },
    controllerAs: 'reviewFormCtrl'
  };
});

答案 1 :(得分:0)

正如@Dustin Hodges所说,但我建议你采用更清洁的方式

<强>指令:

angular
 .module('myApp')
 .directive('reviewForm',  function(){

  var directive = {
      restrict    : 'E',
      templateUrl : 'partials/review-form.html',
      replace     : true,
      scope       : true,
      controller  : 'ReviewFormController'
      controllerAs: 'reviewformCtrl'
  };

 return directive;

});

<强>控制器:

angular
  .module('myApp')
  .controller('ReviewFormController', ReviewFormController);

  ReviewFormController.$inject = [];//your dependencies

  function ReviewFormController(){

    var vm = this;

    vm.rating = 1;

  }

<强>模板:

<div class="main">
 <book-genres></book-genres>
  <review-form ng-show="reviewformCtrl.rating == 1"></review-form>
</div>

希望我能提供帮助。