2

I'm trying to concat a string with a AngularJS expression in html. See the example above:

angular.module("app", []);
function MyCtrl($scope){
    $scope.item = "Hello";
    $scope.say = function(text){
        alert(text);
    };
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script>
    function openFunctionJS(param){
        alert(param);
    };
</script>
<div ng-app="app" ng-controller="MyCtrl">
    <a ng-click="say(item + ' World')">Say {{item}} World by ngclick</a><br/>
    <a onclick="openFunctionJS('{{item}}')">Say {{item}} World by onclick</a>
</div>

http://jsfiddle.net/murphycwb/zr3cc4od/

But it doesn't work. My entire function is in JavaScript and I don't want to change it right now if possible.

What am I doing wrong?

0

1 Answer 1

1

The error thrown by AngularJS is quite specific when you try to do this

Interpolations for HTML DOM event attributes are disallowed. Please use the ng- versions

This is not problematic though, for the framework offers ng- solutions for these events. I see you're already using ng-click, so why not leverage it to solve this as well? If your goal is to keep openFunctionJS untouched, no problem- just call it within $scope.say. Here is an idea...

note - I have altered your definition for MyCtrl. Use of global functions as controllers is generally discouraged

<script>
function openFunctionJS(param) {
    alert(param); // this is called inside $scope.say()
};
</script>

<a ng-click="say(item + ' World')">Say {{item}} World from ng-click</a>

angular.module('app', []).controller('MyCtrl', function($scope) {
    $scope.item = 'Hello';
    $scope.say = function(text) {
        openFunctionJS(text)
    };
});

JSFiddle Link - working demo

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks man, works perfectly! But, only for knowledge, Is there any way to do that while keeping the onclick?
through markup - no. Thats what events like ng-click, ng-blur etc are for

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.