mok mok - 1 year ago 66
AngularJS Question

cannot get the attribute of html tag in angular

I want o get the value of and attribute in my angular controller but it is

. If it helps everything is inside an application.

The simplified codes:


.controller('TestCtrl', ['$scope', '$element', '$attrs', function ($scope, elem, $attrs) {
$ = "mohsen";
$scope.api = $attrs.api;
console.log('hi, I am here');


var app = angular.module('CMM', ['ngRoute','slServices', 'slControllers', 'ngAnimate', 'smart-table', 'ui.bootstrap']);


<div id="content" ng-controller="TestCtrl">
<input type ="text" ng-model="name"/>
<input type="text" ng-model="api" api="/sl/asdf"/>

Answer Source

Your code is not working as written because $element and $attrs are not injectable. As discussed in the comments, you can use a directive to get access to the attributes and reference the controller from the directive. This is not really the proper way to do this, but it can be made to work.

So your controller could expose a method that is used to provide it with the API value from the directive, like this:

.controller("TestCtrl", function ($scope) {
    this.SetApi = function (api) {
    $scope.api = api;

And your directive can reference the controller and call the method to supply the value, like this:

.directive("getApi", function () {
    return {
    controller: "TestCtrl",
    link: function (scope, element, attr, controller) {

Here is a working example:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download