【问题标题】:Passing a value from controller to directive AngularJs将值从控制器传递到指令 AngularJs
【发布时间】:2015-05-03 18:28:55
【问题描述】:

我想将一个值从控制器传递给指令,但视图中的指令可以被覆盖。

示例控制器

    var controllers = angular.module('Project.Controllers.ActionBarCtrl', []);
    controllers.controller('ActionBarCtrl', ['$scope','$rootScope', 
        function($scope, $rootScope){
        $scope.buttonColor = 'red' 
}]);

那么在我看来有两种可能的加载方式

<div my-button button-color='green'></div>

<div my-button></div>

在指令中我要传递按钮颜色(第一个 div 中为绿色,第二个 div 中默认为红色),这是我的指令

sharedDirectives.directive('myButton', function () {
    return {
        restrict: 'A',
        transclude: true,
        scope: {
            'buttonColor': '@'
        },
        template: '<div>' +
                    '<button class="uifw-frm-button small {{buttonColor}}" ng-click="showHideInner()">
                 + </div>

我可以让它与第一个 div 一起工作,并使用绿色值填充 buttonColor 属性,但是当我将它排除在外并想要返回红色时,我得到的值是未定义的。

【问题讨论】:

    标签: angularjs angularjs-directive


    【解决方案1】:

    使用ng-class

    template: '<div>' +
                '<button class="uifw-frm-button small" ng-class="{'red':!buttonColor,buttonColor:buttonColor}" ng-click="showHideInner()">
             + </div>
    

    【讨论】:

      【解决方案2】:

      尝试将编译功能添加到您的指令中:

      compile: function(element, attrs)
      {
         if (!attrs.buttonColor) { attrs.buttonColor= 'red'; }
      }
      

      或在指令的控制器中:

      controller: function($scope){
          $scope.buttonColor = $scope.buttonColor || 'red';
        }
      

      好的,带有编译功能的那个:

      http://jsfiddle.net/eYJqC/

      【讨论】:

      • 感谢您的回答,我试了一下,但是在单击按钮后需要更多功能,并且“编译:...”停止执行任何进一步的代码。所以我使用的答案是我上面选择的那个。我不知道如果我在编译后做错了什么,但这不允许任何其他代码运行。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多