【问题标题】:How to pass the value from controller to directive in angular js如何在角度js中将值从控制器传递到指令
【发布时间】:2016-12-19 00:18:39
【问题描述】:

你好,

我想将一个值从控制器传递给 angularjs 中的指令。我将如何传递值并在指令中显示它。

在 Html 部分

在控制器部分 我的控制器名称是 docontroller。

$scope.name = "世界";

angular.element(document.querySelector('#carControls')).append($compile( mydirectivename 作为标签 )($rootScope));

我必须传递我的变量以及我可以在我的指令中直接访问的控制器 这是我在控制器中使用的指令并附加到 html 在我的指令部分

myApp.directive('Controls', function ($compile, $rootScope, $timeout, $window) {
    var linker = function (scope, element, attrs) {
alertr('name' + scope.name);      
  $timeout(function () {

            scope.controlClass = 'fa fa-pause';
            var ControlsTemplate =

                '<button class="btn btn-default btn-sm margin-r-10 text-center"><i class="fa fa-backward"></i></button>'+
                '<button ng-click="doPlayOrPause()" class="btn btn-default btn-sm margin-r-10 text-center"><i id="play-pause" ng-class="controlClass"></i></button>'+
                '<button class="btn btn-default btn-sm margin-r-10 text-center"><i class="fa fa-forward"></i></button>'+
                '<button ng-click="doStop()" class="btn btn-default btn-sm margin-r-10 text-center"><i class="fa fa-stop"></i></button>';

            element.html(ControlsTemplate);
            $compile(element.contents())(scope);



        });  
    };
    return {
        restrict: "E",
        replace: true,
        link: linker
    };
});

作为回报 我通过了控制器:'docontroller bt 我在范围内找不到我的名字'

【问题讨论】:

  • 你可以使用 $watch 来访问指令中的作用域值
  • 你为什么要这样做...获取元素并使用 $compile 追加...您需要克服 jquery 的做事方式...

标签: angularjs controller directive


【解决方案1】:

在你的控制器中

$scope.yourValue="myValue";

在你的指令中

app.directive('myDirective',function(){
 return {
        restrict: 'E',
        scope: {
            yourValue: '='
        },
})

在你的 dom 中

<my-directive your-value="yourValue"></my-directive>

查看此js fiddle

【讨论】:

  • 我想在指令中显示它
  • 这是正确的做法,向我们展示此解决方案的无效代码
  • angular.element(document.querySelector('#carControls')).append($compile('')($rootScope)) ;
  • 仍然没有显示在指令中
【解决方案2】:

如果您没有使用隔离范围,则可以访问父控制器 $scope。

您也可以使用 $rootScope。

喜欢

控制器:

app.controller("demoCtrl",function($scope,$rootScope){

   $rootScope.xyz = "test";
// call your directive , value will be accessible in directive
})

指令:

app.directive(...,function($rootScope){
 return   {
 // extra code omitted.

  // get your value here like
  // var abc =  $rootScope.xyz;

}
)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-13
    • 1970-01-01
    • 2018-09-03
    相关资源
    最近更新 更多