mok mok - 1 month ago 7
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

undefined
. If it helps everything is inside an MVC.net application.

The simplified codes:

TestCtrl.js:

angular.module('CMM')
.controller('TestCtrl', ['$scope', '$element', '$attrs', function ($scope, elem, $attrs) {
$scope.name = "mohsen";
$scope.api = $attrs.api;
alert($attrs.api);
alert(elem.data('api'));
console.log('hi, I am here');
}]);


app.js:

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


usage:

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

Answer

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) {
      controller.SetApi(attr.api);
    }
  };
});

Here is a working example: https://jsfiddle.net/n5t6pfcc/

Comments