将范围变量传递给指令的控制器

时间:2017-03-02 01:29:54

标签: angularjs directive

我的指令在js文件中有单独的控制器,它有一个范围变量parameterDatabase,需要从调用页面填充。我无法找到将值传递给它的方法。

<body ng-app="testAPP" ng-controller="ctl">
Directive Here
<my-cust parameterDATABASE="dt"></my-cust>

<script >
    APP = angular.module("testAPP",['schedule']);

    APP.controller("ctl",function($scope)
                  {
                    $scope.dt = {date:"02-03-2017",sDay:"Thu",sTime:"01:00"};
    }) // end of controller

    APP.directive("myCust",function()
    {
        return{
                scope:{
                    parameterDATABASE:'='
                },
                controller:"scheduleCtrl",
                templateUrl:"templateForDirective.html"
              }
    })
</script>

scheduleCtrl也有一个变量parameterDATABASE。

指令控制器的一部分

var APP = angular.module('schedule',[]);
 APP.controller('scheduleCtrl',function($scope,$filter) 
{ $scope.parameterDATABASE=[]; // This is the variable I want to populate

..............

1 个答案:

答案 0 :(得分:0)

1)根据一些角度命名约定,指令的属性名称应转换为 camelCase

因此,parameterDATABASE中的 html Directive parameter-database

因此,在指令中,你应该使用它,

scope: {
       parameterDatabase: '='
}

因此,parameterDatabase映射到==&gt; parameter-database

2)您也可以直接在两个地方使用parameterdatabase,而无需大写。

例如:parameter-database="dt"

中的html directive
  scope: {
           parameterdatabase: '='
    }

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body ng-app="myApp" ng-controller="ctl">

<isolate-scope-with-controller parameter-database="dt" add="addCustomer()"></isolate-scope-with-controller>

<script>
var app = angular.module("myApp", []);

 app.controller("ctl",function($scope)
                  {
                    $scope.dt = {date:"02-03-2017",sDay:"Thu",sTime:"01:00"};
    }) // end of
    
  app.directive('isolateScopeWithController', function () {
      
    var controller = ['$scope', function ($scope) {
		console.log($scope.parameterDatabase)

      }],
        
      template = '<h1>I am from directive controller</h1><br><h2>{{parameterDatabase}}</h2>';
      
      return {
          restrict: 'EA', //Default in 1.3+
          scope: {
              parameterDatabase: '='
          },
          controller: controller,
          template: template
      };
  });


</script>

</body>
</html>

请跑上面的SNIPPET

Here is a working DEMO