2016-03-09 75 views
0

我想从一个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中我可以检查参数的值吗? 有没有更好的选择来实现这一目标?

感谢,

回答

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> 
+0

对不起,我不明白这一点。上面的建议是否将someParam传递给控制器​​? –

+0

很高兴我能帮到你 –

0

如果不使用隔离范围(范围:{someparam: “”}),然后你可以使用该指令模板任何$作用域属性不改变任何东西:

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

谢谢!

指令

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

控制器

console.log($scope.param); 

日志确实指定的值。 非常感谢!