将参数从html指令传递给控制器

时间:2016-03-09 13:48:35

标签: javascript html angularjs angularjs-directive

我想将一个参数从html指令传递给控制器 例如:

指令:

angular.module('app')
   .directive('helloWorld', function () {
  return {
      replace: false,
      restrict: 'AE',
      templateUrl: "./views/templates/helloWorld.html" 
  }
});

的helloworld.html:

<body ng-app="app" >
<div ng-controller="HelloWorldCtrl">
{{ welcome }}
</div>

hello.html的:

<body ng-app="app">
<hello-world/>
</body>

HelloWorldCtrl:

angular.module('app')
.controller('HomeWorldCtrl', function ($scope, ) {

    $scope.welcome = "Welcome"

    };
})

我可以在hello.html中指定参数,例如

<hello-world param="param1"/>

那是传递给控制器​​的? 那么在HomeWorldCtrl中我可以检查参数的值吗? 有没有更好的替代方案来实现这一目标?

谢谢,

3 个答案:

答案 0 :(得分:0)

app.directive('helloWorld', function(){
return {
  restrict:'E',
  scope: {
     param: '@'
  },
  template:'<div class="param"><h2>{{param}}</h3></div>'
};
});

// you have options to choose from

//= is two-way binding
//@ simply reads the value (one-way binding)
//& is used to bind functions

<hello-world="someParam"></hello-world>
//    for the scope definition:

scope: {
title: '@helloWorld'
}
The usage in the template will remain the same

<hello-world param="someParam"></hello-world>

答案 1 :(得分:0)

如果您不使用隔离范围(范围:{someparam:“”}),那么您可以在指令模板中使用任何$ scope属性而不更改任何内容:

$scope.param = "new param value";
..
return {
  ..
  ,template: "<param>{{param}}</param>" 

答案 2 :(得分:0)

谢谢!

指令

Addons.xcu

控制器

   return {
      replace: false,
      restrict: 'AE',
      templateUrl: "./views/templates/PatientSearchEdit.html",
      scope: {
          param: '@'
      }
  }

确实记录指定的值。 非常感谢你!