如何更改控制器

时间:2015-08-11 09:48:54

标签: angularjs angularjs-directive angularjs-scope

指令列表如下:

HTML:

<div ng-app="dashboard" ng-controller="MyCtrl">
    <button class="btn btn-white" ng-click="minim()"><i class="fa fa-minus-square"></i></button>
    <widget-item widget-id="1" widget-type ="chart"></widget-item>
    <widget-item widget-id="2" widget-type ="table"></widget-item>
</div>

JS:

var dashboard = angular.module("dashboard",['ui.bootstrap','ngAnimate']);
dashboard.controller( 'MyCtrl', function ( $scope,$modal) {
    $scope.on = true;
    $scope.minim = function(){
        $scope.on = !$scope.on;
    };
});
dashboard.directive('widgetItem', ['$compile', function($compile){
        restrict: 'E',
        scope:true,
        template: '<div class="panel"><div class="panel-heading"><div class="mypanel-btn" > <a href="" class="mypanel-minimize"  ng-click="toggle()"><i class="fa fa-minus"></i></a></div></div><div class="panel-body" ng-show="on"></div></div>',
        link:function(scope, element, attrs) {
                scope.on = true;
                scope.toggle = function () {
                   scope.on = !scope.on;
                };
        }
}]);

这里我有个别指令的最小化按钮以及所有指令。个别最小化按钮工作正常(它在指令链接中定义)。所有最小化按钮都不起作用。如何从控制器更改指令隔离值?

2 个答案:

答案 0 :(得分:0)

在您的情况下,您可以使用 $ broadcast ,它将发出事件并将事件向下发送到所有子范围。

然后,您可以使用 $ on 将某个事件收听到您的指令中。

如果我按照你的代码:

<强>控制器

(function(){

function Controller($scope, $http) {

    $scope.on = true;

    $scope.minim = function(){
      $scope.on = !$scope.on;
      //send minim event downwards to all child scope
      $scope.$broadcast('minim', $scope.on);
    };

}

angular
.module('app', [])
.controller('ctrl', Controller);

})();

<强>指令

(function(){

  function widgetItem($compile) {
      return{
        restrict: 'E',
        scope: true,
        templateUrl: 'template.html',
        link:function(scope, element, attrs) {

          //Listen event minim
          scope.$on('minim', function(e, data){
            //Change our scope.on data
            scope.on = data;
          });

          scope.toggle = function () {
             scope.on = !scope.on;
          };
        }
        };
  }

angular
  .module('app')
  .directive('widgetItem', widgetItem);


})();

然后,请致电您的指令:

<强> HTML

  <body ng-app="app" ng-controller="ctrl">
    <button class="btn btn-white" ng-click="minim()"><i class="fa fa-minus-square"></i></button>
    <widget-item widget-id="1" widget-type ="chart"></widget-item>
    <widget-item widget-id="2" widget-type ="table"></widget-item>
 </body>

答案 1 :(得分:0)

如果您将指令与scope: true一起使用,则意味着您的新范围是父范围的子节点,您可以更改所需的任何内容,因为它不是孤立的范围。

如果你需要更多的例子,这里有一篇很酷的文章

http://www.w3docs.com/snippets/angularjs/change-variable-from-outside-of-directive.html