当指令中已经给出范围时,如何访问在控制器中声明的函数

时间:2016-05-02 09:57:04

标签: javascript angularjs angularjs-scope

我尝试制作一个自定义指令(这里是一个进度条)。这是HTML中的声明:

<body ng-app="progressBar" ng-controler="progressBarCtrl">
<pb widthb="20" heightb="100"></pb>
<button ng-click="setProgress(10)">set to 10</button>
</body>

这是我的模块声明:

angular.module('progressBar', [])
//
// Directive that generates the rendered chart from the data model.
//
.directive('pb', function() {
  return {
    restrict: 'EA',
    templateUrl: "flowchart/progress-bar.html",
    replace: true,
    controller: 'progressBarCtrl',
    scope :{
     widthb: '=',
     heightb: '='
    }
  };
})
.controller('progressBarCtrl', ['$scope', function progressBarCtrl ($scope) {
 $scope.progress=60;
 $scope.setProgress = function (value) {
  if (value>100){
    value=100;
  }
  if (value<0){
    value=0;
  }
  $scope.progress=value; 
 };
}]);

点击“设为10”按钮将永远不会调用该功能。

Plunker

3 个答案:

答案 0 :(得分:0)

试试这个:

.directive('pb', function() {
  return {
    restrict: 'EA',
    templateUrl: "flowchart/progress-bar.html",
    replace: true,
    controller: 'progressBarCtrl',
    bindToController: {
      widthb: '=',
      heightb: '='
    },
    scope: true
  };
})

这会让setProgress()工作吗?

答案 1 :(得分:0)

你正在用html写错字,写ng-controller而不是 ng-controler

如果您尝试这样做也很有用:

<html ng-app="progressBar">
  <body ng-controller="progressBarCtrl">
  <pb widthb="20" heightb="100"></pb>
  <button ng-click="setProgress(10)">set to 10</button>
  </body>
</html>

答案 2 :(得分:0)

答案表单oguzhan00应解决您的问题。

但在这种情况下,您不必在body标签上实际定义ng-controller。从您的代码我认为您正在尝试为您的指令创建一个控制器。在这种情况下,您不需要html中的ng-controller。当您的指令被评估时,控制器也将自动实例化。您需要做的唯一事情是将按钮标记移动到指令的templateUrl,因为范围将仅在该html中。这也将解决问题。

当您对指令使用角度控制器时,最好使用controllerAs语法,因为当应用程序很大时,我们很可能会与范围混淆,因此总是建议使用别名。